Why doesnt Gameobject.find not work?

I’m using Gameobject.find, but it won’t return anything

	public float smooth = 1F;
	public GameObject thePlayer;

	void Start(){
		thePlayer = GameObject.Find("PlayerCameraPosition");
	}

	void Update () {
		if(transform.position.x != thePlayer.transform.position.x){
			transform.position = Vector3.Lerp(transform.position, thePlayer.transform.position, Time.deltaTime * smooth);
		}

		if(transform.position.y != thePlayer.transform.position.y){
			transform.position = Vector3.Lerp(transform.position, thePlayer.transform.position, Time.deltaTime * smooth);
		}
	}

That’s my script on the camera, its suppose to find the position parented to the player, so the camera can lerp to it… in theory, but it never finds anything. As you can see, it is in the hierarchy
65249-capture.png
But it just never works, anyone help?

PlayerCameraPosition is a child of NetworkPlayer and therefore a transform and not a GameObject.

Instead you should probably do something like this

thePlayer = GameObject.Find("NetworkPlayer");
thePlayerPosition = thePlayer.transform.GetChild(0);

I believe that Transform.Find will also work but I think that would probably be less efficient (and GameObject.Find is hardly efficient at the best of times). Using GameObject.FindWithTag will be a bit more efficient but if ‘NetworkPlayer’ means that you are trying to create a multiplayer environment you will need a better solution in the end.

Hello, @Namaarie.

There are many reasons to why GameObject.Find would fail. A common reason is calling it before the instantiation of the object that it seek.

This is probably what is happening:

  • ( … )
  • Call GameObject.Find
  • ( … )
  • Call Object.Instantiate

In short, we cannot find something that has not been instantiated.

Hello, @Namaarie
GameObject may not have been created before you call GameObject.Find
Make sure your GameObject is Instantiate before GameObject.Find is called