- Home /
transform.Find always returns null
I created a script to fire projectiles from the barrel of a weapon. Everything works fine until I try to get the grandchild that is the point where the projectile is created (weaponHardpointVector[i] = transform.Find("EnemyTankTurret/EnemyWeapon1");:
if(equippedWeapons[0] != null){
while(i < equippedWeapons.Length){
//Debug.Log ("Number of Equipped Weapons: " + equippedWeapons.Length);
GameObject weapon = Instantiate(equippedWeapons[i], transform.position, transform.rotation) as GameObject;
//Debug.Log("Enemy Weapon Created: " + weapon.name);
weapon.transform.parent = transform;
weaponBay[i] = weapon.GetComponent<WeaponStats>();
Debug.Log("Weapon Bay 1: " + weapon.GetComponent<WeaponStats>());
weaponHardpointVector[i] = transform.Find("EnemyTankTurret/EnemyWeapon1");
Debug.Log ("I Found : " + transform.Find ("EnemyTankTurret/EnemyWeapon1"));
Debug.Log ("Barrel Vector: " + weaponHardpointVector[i]);
i++;
b++;
}
}
I keep getting:
Enemy+c__Iterator3.MoveNext () (at Assets/Scripts/Enemy.cs:103) UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator) Enemy:Update() (at Assets/Scripts/Enemy.cs:91) I've checked the hierarchy and that all the spelling is correct. I've tried moving the object up to be a child instead of a grandchild and it still returns null. Am I using transform.Find() incorrectly?NullReferenceException: Object reference not set to an instance of an object
As far as I know, Find
doesn't work with the hierarchy, so it would only be ËnemyWeapon1"
. But I might be wrong XD
Answer by dchen05 · May 21, 2013 at 12:18 AM
Its tough to say without seeing your hierarchy and on which object the script is located. transform.Find() looks in everything thats part of that transform that the script is on. So if your script is on EnemyTankTurret, you would only need to put
transform.Find("EnemyWeapon1")
Also remove the slash from the name of EnemyTankTurret, slashes in gameobject names makes Unity confused, as it looks for them to be indicators of parent children relationships, like folders. http://docs.unity3d.com/Documentation/ScriptReference/Transform.Find.html
The script is on EnemyTurret (the parent object). Let me get a screenshot of the hierarchy.
Try removing the slash from the name of EnemyTankTurret, slashes in gameobject names makes unity confused. http://docs.unity3d.com/Documentation/ScriptReference/Transform.Find.html
Interesting. I had tried it before without the "/" and it wasn't working. I guess something else was broken and I broke it more trying to fix it :/. Anyway, if you copy the above post as the answer I'll mark it.
Thanks for the help!