enter code hereSo I have 2 objects. A sphere called “Ball” and a Square called “AttackCube”. When my attackcube collides with my ball, the ball is destroyed. But I have code that make my sphere constantly looking for the ball and so I get the error message “MissingReferenceException: The object of type ‘Transform’ has been destroyed but you are still trying to access it” This is my code trying to fix it, but it doesn’t work:
#pragma strict
var speed:int;
var target :Transform;
var minRange:int;
var follow:boolean;
function Update(){
//I added onto this "&& "Ball!= null, but it doesn't seem to work.**
if(Vector3.Distance(transform.position,target.position) < minRange && "Ball" != null)
follow=true;
if(follow){
transform.LookAt(target);
transform.Translate(Vector3.forward * Time.deltaTime * speed);}
}
First of all the language is called UnityScript (or if you prefer “JavaScript” even when it’s just similar to JavaScript) and has no relation to Java which is a completely different language.
Next thing is the condition
"Ball" != null
makes no sense since you compare a string constant to null which is always true.
Furthermore if your target variable is null because the object it references got destroyed, you have to do the null check before accessing target.position.
This should work:
#pragma strict
var speed : int;
var target : Transform;
var minRange : int;
var follow : boolean;
function Update()
{
if (target != null)
{
if(Vector3.Distance(transform.position, target.position) < minRange)
follow = true;
if(follow)
{
transform.LookAt(target);
transform.Translate(Vector3.forward * Time.deltaTime * speed);
}
}
}
It’s not Java. It’s Javascript! They are not even close to the same thing! Javascript is named Javascript because Java was the big deal around when Javascript came out. The real name ™ would be ECMAScript, and Unity uses a variant of this (a “dialect”, if you will), that’s popularly referred to as “UnityScript”, as to distinguish it from the “normal” Javascript.
Oh and your bug is that you’re checking this:
"Ball" != null
IE. checking if the string (word) “Ball” is null. Which it is not - it is “Ball”. What you want is if the object - or rather the transform you’re trying to follow - is not null. You also want to check it before you get the Distance, and the extra variable ‘follow’ isn’t really necessary: