- Home /
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[i].transform.position);
if(tempDist < dist) {
closestpet2 = pet2[i];
}}
}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;
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
Answer by Statement · Mar 24, 2011 at 07:22 PM
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?
Answer by Paul 7 · Mar 24, 2011 at 07:31 PM
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.
Your answer
Follow this Question
Related Questions
2D Animation does not start 1 Answer
How to change value of var of a disabled component? 0 Answers
disable/enable script js 2 Answers
How to fix mouse Look X and Y sensitivity (built-in script) 3 Answers