- Home /
Trouble setting up a vector 3.
I'm trying to create a vector3 variable that is equal to the position of a child object using this code:
Transform doorPointPosition =
this.gameObject.transform.Find("DoorPointNorth");
Vector3 doorPoint = (doorPointPosition.position);
DoorPointNorth is the name of the child that I'm trying to get the position of, so that I can use it as a vector3 position later.
For some reason I keep getting a Null reference error. I've checked through the code and the name I've specified for the transform.Find is definitely correct. What am I doing wrong here, and how could I fix it?
Any help would be appreciated, thanks.
Your code actually should work. Can you post how your hierarchy looks like and to which object in the hierarchy this script is attached to?
Are you sure that "DoorPointNorth" is a direct child of the object this script is attached to?
btw: This is double redundant:
this.gameObject.transform.Find(
it's the same as
transform.Find(
Thanks, That helps make the code look a little neater. The problem's actually been solved. I might of misunderstood what parenting and children are - as simply using GameObject.find to get the DoorPointNorth worked fine.
An understandable mistake, but once you know about the distinction its actually convenient to have both a wide search with GameObject.Find and a shallower search with transform.Find().
Answer by ThatsAMorais · Dec 17, 2013 at 09:23 PM
Perhaps the object you're looking for is not a child of "this". I would suggest you use.
GameObject.Find("DoorPointNorth");
This worked, but now I'm worried - Due to how I have several prefabs each with their own "DoorPointNorth" object, how will I be able to specify which prefab's "DoorPoint" it is that I'm using?
You can add tags to game objects.
GameObject.FindGameObjectsWithTag("DoorPointNorth");
Tag each DoorPointNorth with a different tag.
I've managed to set up a workaround similar to what you suggested, only I've set the code to rename each object to something with a unique number on the end when it's instantiated, and that works fine.
It might be horribly bad coding, or inefficient as all hell but it works, so I'm not so bothered right now
I often use hierarchy. The way you "set parent" is through the transform. So, I would create the DoorPointNorth from the object with which its associated, and then assign the parent like this.
doorPointInstance.transform.parent = transform;
That will set the parent of DoorPointInstance to the transform that created it. At the very least you can use gameObject.Find("") to get it, but I would store it and make a public accessor function.