Refrencing components: What am I doing wrong here? (probably simple)

}if(pet2.length > 0 && pet2!=null) {        
                var closestpet2 = pet2[0];        
                var dist = Vector3.Distance(transform.position, pet2[0].transform.position);       

                for(var i=0; i < pet2.Length; i++) {            
                var tempDist = Vector3.Distance(transform.position, pet2*.transform.position);* 
 *if(tempDist < dist) {* 
 _closestpet2 = pet2*;*_ 
 _*}}*_
 _*}if (closestpet2!=null && Vector3.Distance(closestpet2.transform.position, transform.position ) <=5 )*_
 _*if(held01)*_
 _*if(Input.GetMouseButtonUp(1))*_ 
 _*if (closestpet2.GetComponent(Follow).equip03== false){*_
 _*transform.parent = closestpet2.GetComponent("petmouth2").transform;*_
 _*transform.position = closestpet2.GetComponent("petmouth2").transform.position;*_ 
 _*closestpet2.GetComponent(Follow).equip03=true;*_
 _*held01=false;*_
 _*held03 = true;*_
_*```*_
_*<p>on the transform parent = etc & transform.positon = etc, the editor keeps giving me errors about how it's a null reference exception. I'm trying to equip items the player is holding to the 'closestpet2's mouth by mouseclick.*_
 _*Thanks for any help</p>*_

2 Answers

2

If you're getting null reference exceptions it means you don't have a component called "petmouth2" on closestpet2. Are you sure you have a script that is called exactly "petmouth2"? Are you sure you aren't looking for a child instead of a component? You can use Find to find a child if that's what you're looking for, since it makes no sense to get the transform of a component of an object because it would be the same transform as closestpet2.transform.

How would I write that? The pets mouth is an empty game object child positioned at the mouth of the character. THis is the script is on the item itself

transform.parent = transform.Find("closestpet2/petmouth2"); transform.position = transform.Find("closestpet2/petmouth2").position; I tried this with the link but it's still not going- what am I missing?

try closestpet2.transform.Find("petmouth2"). Are you really sure this is where the program crashes?

This is the case in C# and i dont see why it wouldnt be in Java but with the statement:

if(pet2.length > 0 && pet2!=null)

the if statement checks pet2.length > 0 first and if pet2 IS null then a null reference will get thrown.

For it's 'petmouth' gameobject? When I start the player atleast 2 pet2s are active. I am using Java

What he means is you're checking pet2 for null in wrong order. Paul means that you should write if (pet2 != null && pet2.length > 0) since otherwise you can get a null reference exception when doing pet2.length.