- Home /
Null Reference with transform
Im trying to make my var Player move to the position of the object Waypoint. Player is an empty in my game and WayPoint and PlayerObj are both children of it. I thought i had it but whenever i run it i get a null reference. any help would be great
here is my code:
var Moving : boolean = false;
var speed : int = 5;
function Update(){
var waypoint = transform.Find("WayPoint"); var player = transform.Find("PlayerObj");
if (Moving == true){
player.position = Vector3.MoveTowards(player.position, waypoint.position, speed*Time.deltaTime);
}
}
function ActiveMove () {
Moving = true; }
Answer by Seth-Bergman · Jul 20, 2012 at 05:20 AM
for starters, get that line out of the update and into the start function... make sure you declare the vars outside the function.
otherwise, you should print the null reference for clarity.. maybe the name is not exactly correct? or maybe you are trying to access the vars player or waypoint from another script? can we see the null reference please
I'm not exactly sure how to print a null reference sorry I'm still kind of a noob. But heres the line from the debugger, NullReferenceException
UnityEngine.Transform.get_position () (at C:/BuildAgent/work/b0bcff80449a48aa/Runtime/ExportGenerated/Editor/UnityEngineTransform.cs:19) Player$$anonymous$$ove.Update () (at Assets/Scripts/Player/Player$$anonymous$$ove.js:20)
I also moved the variables outside like you suggested
looks like the null reference is co$$anonymous$$g from the script "Player$$anonymous$$ove", on line 20. What is on line 20?
also, I suspect the prob is "var player = transform.Find("PlayerObj");"
understand that Transform.Find uses the exact hierarchy, so only if PlayerObj is directly childed to Player will this work..
Line 20 reads :
Player.position = Vector3.$$anonymous$$oveTowards(Player.position, Waypoint.position, speed*Time.deltaTime);
and both PlayerObj and Waypoint are two separate children of the empty named Player so i believe that makes them both direct children
Your answer
![](https://koobas.hobune.stream/wayback/20220613074434im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
move childA to position of childB 1 Answer
Move Object Left/ Right 0 Answers
Waypoint System help 1 Answer
Best Way to make a character move 1 Answer