I wanted this code to send a "no" when it doesn't find the object "Player_1" but when it finds it, it sends "yes" in the debug log but when I remove it simply don't send na
public GameObject _objeto1;
public GameObject _objeto2;
public float _distancia1;
public
void Start()
{
_distancia1 = 0;
}
void Update()
{
_objeto1 = GameObject.Find("Player_1");
_distancia1 = Vector3.Distance(_objeto1.transform.position, _objeto2.transform.position);
if (_objeto1 == true)
{
Debug.Log("sim");
}
else
{
Debug.Log("nao");
}
}
}```
CodePudding user response:
Try this:
public GameObject _objeto1;
public GameObject _objeto2;
public float _distancia1;
void Start()
{
_distancia1 = 0;
}
void Update()
{
_objeto1 = GameObject.Find("Player_1");
if (_object1 != null)
{
_distancia1 = Vector3.Distance(_objeto1.transform.position, _objeto2.transform.position);
}
if (_objeto1 != null)
{
Debug.Log("sim");
}
else
{
Debug.Log("nao");
}
}
CodePudding user response:
Thank you for question!
GameObject.Find() returns GameObject if it's exist on scene and returns "null" when there is no object. So you can use if statment to check if _objeto1 is null.
_objeto1 = GameObject.Find("Player_1");
if (_objeto1 == null)
{
Debug.Log("nao");
}
else
{
Debug.Log("Yes");
}
And don't use '_' for public fields. It's bad practice. You can use it for private fields.