Set transform from another GameObject's script
gameobject, instantiation, unity-game-engine, unityscript
Solution
The code you posted can't be right. You are using the PlayerPrefab's name to to find the Camera Control script attached to the camera? By that logic then the moment you instantiate `PlayerPrefab`, on the second line, you will have a second camera.
I think what you want to do is this: Instantiate the player prefab and make the camera point to the player.
So I am assuming the `CameraControl` script is created. You need the following before we start to code.
Attach `CameraControl` script to the camera in the scene.
Make sure the `Player` script is attached to the Player Prefab.
Have a third script that will instantiate the PlayerPrefab. I will call it `Instantiator`. Attach it to an empty GameObject in the scene, think of it as the world GameObject. We will call it World.
Make sure the `Instantiator` script is attached to the World GameObject and that it is pointing to the PlayerPrefab.
Code: Instantiator
The `Instantiator` script will spawn and create things we will use in the scene.
#pragma strict
var PlayerPrefab : GameObject;
function Start ()
{
// You can add position and rotation to the function call if you like.
var p = Instantiate(PlayerPrefab) as GameObject;
// Find the camera script and point to Player's transform.
Camera.main.GetComponent("CameraControl").SendMessage("setTarget", p.transform);
}
Notice I used the fact that the MainCamera in the scene is marked by Unity for you so it is easy to find.
Code: CameraControl
The `CameraControl` will have the logic to follow the Player as you see fit. Notice that target will point to what the camera will focus on. Of course following the Player around you will have to write.
var target : Transform;
function setTarget(t : Transform)
{
target = t;
}
I just taught myself a bit of JavaScript. I had never used it before.
Problem
I'm trying to make a script to set an object when is being instantiated. The problem is, I don't clearly know how to do it. I have this function.. ``` function spawnPlayer() { var CameraScript = GameObject.Find(PlayerPrefab.name).GetComponent("Camera Control"); Network.Instantiate(PlayerPrefab, spawnObject.position, Quaternion.identity, 0); } ``` Where PlayerPrefab is going to be the Prefab that's going to be instantiated. When this happens, I need to set the instantiated gameObject on another GameObject which is camera and has a script called "Camera Control" and inside there's a transform Target which I'm trying to set. How to do this?