- Home /
Referencing instantiated player in camera's Start()
Hey guys, I'm instantiating my player in the Start() of my GameController script, and then referencing it in my Main Camera so that I can track the player's movement each frame with the camera.
BUT - When I reference the player by tag in the Start() of my camera script, it doesn't find it. I assume this is because the camera's Start() is run before the player is instantiated, so can't find it. So what should I do? Could I delay the camera so that it looks for the player AFTER it's instantiated? Should I instantiate the Main Camera too?
Here's my GameController script:
private var playerSpawn : GameObject; // a dummy object to mark where player starts
function Start () {
playerSpawn = GameObject.Find("PlayerSpawn");
var playerInstance : GameObject = Instantiate(
Resources.Load("Player", GameObject),
Vector3(playerSpawn.transform.position.x, 0, playerSpawn.transform.position.y),
playerSpawn.transform.rotation);
}
And the camera script:
public var player : GameObject;
function Start () {
player = GameObject.FindGameObjectWithTag("Player");
}
function Update () {
transform.position.x = player.transform.position.x;
transform.position.z = player.transform.position.z - 3.2;
var camerapos = transform.position - player.transform.position;
}
Answer by revolute · Jun 01, 2015 at 08:04 AM
One option is keeping camera script disabled (even in the scene so that Start() will never occur) until you have instantiated player.
The other option is adding the camera script after you have instantiated player.
Another option is adding Init() to camera script and invoke it after you have instantiated player. Of course, you would have to do if(player != null) check, but in my opinion, this is more reliable.
I'm not sure how to add the scripts in a specific order. I've accepted your answer but what I've actually done to solve the problem is decided not to instantiate the player at all, I'll just place it in the scene manually.
Answer by Ryzokuken · Jun 01, 2015 at 08:09 AM
Do you know that Instantiate does not only create an instance, but returns the gameobject as well.
GameObject go;
go = instantiate(prefab) as GameObject
I don't think I'm quite knowledgeable yet in Unity to understand your answer. Are you saying there's a better way to do what I'm doing?
Actally, what I am saying is, that:
You are instantiating a character.
You are trying to get a reference to your character using
GameObject.Find()
,GameObject.FindObjectWithTag()
and what not.
Actually, the Instantiate()
function in Unity has multiple overloads, including one which returns the Object which you're instatiating, which can be easily typecasted to a GameObject.
Simply put,
Rather than:
Instatiate(myPrefab);
You can:
GameObject myVariable = Instantiate(myPrefab) as GameObject;
Hope This Helps!