- Home /
I can't assign a GameObject from another script
So I'm trying to make the character look to the closest enemy. And my code for it is this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemyDetect : MonoBehaviour
{
private void OnTriggerStay(Collider targett)
{
if (targett.tag == "Enemy")
{
Player playerScript = GameObject.Find("Character").GetComponent<Player>();
playerScript.target = targett.gameObject;
}
}
}
So basically what I've done is I put in a sphere collider as a child of my character and put this code inside the collider but everytime I run the code it gives an error saying: "UnassignedReferenceException: The variable target of Player has not been assigned. You probably need to assign the target variable of the Player script in the inspector."
Can someone help?
Very likely that the error is not co$$anonymous$$g from this script. Also don't GameObject.Find the character every frame. Your enemyDetect is probably part of the character. Just store the reference in a field somewhere
In Addition to this: setting the target once should be enough. Use OnTriggerEnter instead.
Answer by tfalmeida91 · Oct 15, 2021 at 03:53 PM
You are either trying to access that variable before the OnTrigger event assigns it, or the OnTrigger is not being fired and thus the variable "target" is not assigned.
Just to make sure, in case you don't know or have forgotten:
Make sure the object that detects the Enemies (OnTriggerStay) has a RigidBody and the Collider has the Checkbox "IsTrigger" marked;
Make sure that if you try to access the target variable, to first validate if it is not null "if (target != null)", in case it is, the code keeps running without issues;
If the object must not move, don't tick the "IsKinematic", just check all the Constraints on the RigidBody and it will still detect objects but will be "static";