0

I've created a TileMap. My enemy is a simple cylinder with an "EnemyMover.cs" script attached and is in the scene (hierarchy) before play is pressed. (Not instantiated during runtime)

On a separate object, I have a "TargetLocator" script which attempts to utilize GetComponent to find the cylinder script component when instantiated by click on a tile on the map during runtime.

    public class TargetLocator : MonoBehaviour
{
    [SerializeField] private Transform weapon;
    private Transform target;
    
    void Start()
    {
        target = GetComponent<EnemyMover>().transform;
    }
    
    void Update()
    {
        AimWeapon();
    }

    void AimWeapon()
    {
        weapon.LookAt(target);
    }
}

The error:

NullReferenceException: Object reference not set to an instance of an object TargetLocator.Start () (at Assets/Towers/TargetLocator.cs:12)

Enemy Object with EnemyMover Script

I should mention that I've attempted to:

  1. Reset Unity
  2. remove the transform and verify only the object
  3. Add a rigidbody to the enemy (cylinder)
  4. Add a collider

All still return null except rigidbody but that causes the item to fall through the floor and still doesn't target the enemy.


    public class EnemyMover : MonoBehaviour
    {
        [SerializeField] private List<Waypoint> path = new List<Waypoint>();
        [SerializeField] [Range(0f, 5f)] private float speed = 1f;
    
        void Start()
        {
            StartCoroutine(FollowPath());
        }
    
        IEnumerator FollowPath()
        {
            foreach (Waypoint waypoint in path)
            {
                Vector3 startPos = transform.position;
                Vector3 endPos = waypoint.transform.position;
                float travelPercent = 0f;
                
                // todo reintroduce when object can face
                // transform.LookAt(endPos);
    
                while (travelPercent < 1f)
                {
                    travelPercent += Time.deltaTime * speed;
                    transform.position = Vector3.Lerp(startPos, endPos, travelPercent);
                    yield return new WaitForEndOfFrame();
                }
            }
        }
    }

thielr7
  • 327
  • 3
  • 11
  • Maybe a simple script execution order issue ? To quickly confirm you can try changing `weapon.LookAt(target);` to `weapon.LookAt(GetComponent().transform);` in your `AimWeapon` method. – BenH May 31 '21 at 00:32

2 Answers2

0

Rather than transform , which is the real-world location of a object, try calling a method that is in that script. E.G EnemyMover

 public class EnemyMover: MonoBehaviour
{
    private Transform target;
    
    public Transform CalculateTarget()
    {
        target = GetComponent<Player>().transform;
        return target;
    }
}

Then in TargetLocator you would call:

target = GetComponent<EnemyMover>().CalculateTarget();
StarshipladDev
  • 1,166
  • 4
  • 17
  • Is an example or specific? I don't have anything in my scene that would indicate player. The EnemyMover.cs is on the enemy in which I'm attempting to get the transform for. Could I use target = GameObject... or GetComponent or something like that? – thielr7 May 30 '21 at 23:35
  • I tried your code except I used: ``` target = transform; ``` Still getting NullReference error. – thielr7 May 30 '21 at 23:43
  • @thielr7 Add your `TargetLocator` script to the question in an edit. `target = transform` won't do anything as `transform` is a property of an object, not an actual value – StarshipladDev May 30 '21 at 23:46
  • 1
    I assume you meant the EnemyMover script, as the TargetLocator script is above in its entirety. I've attached the other as an edit. Thanks for looking at this. The strange thing is that I'm watching and following with a Udemy video where the original code I have works for them. – thielr7 May 30 '21 at 23:51
  • @thielr7 try `target = GetComponent().transform;` and then if that doesn't work `target = GetComponent().transform.position`. `EnemyMover` is a script, so will not have a `transform`, but `Enemy` IS a gameobject, so WILL have a `transform` – StarshipladDev May 31 '21 at 00:27
  • No dice. GetComponent() isn't recognized at all in either file, so I'm unable to attempt transform or position. I can get the EnemyMover.cs script to recognize GetComponent()... but the CalculateTarget method used in TargetLocator.cs still leaves the target as null. I've tried it in Awake, Start, and Update. – thielr7 May 31 '21 at 01:46
  • 1
    @thielr7 my bad, I meant use `target=GameObject.Find("Enemy").transform` – StarshipladDev May 31 '21 at 01:48
  • That did the trick. I've always been told to avoid GameObject.Find() at all costs so I hadn't even tried it yet. Maybe I should attempt to put together a tag on the enemy and search for that instead? Either way - Thanks for the help! Answer solved for now. – thielr7 May 31 '21 at 01:54
  • @thielr7 Yeah tagging is much better. Basically the hierarchy goes : GameObject (Use Name, Tags , Drop-and-drag references from the editor) > Transformation (Use /Objectname/.transform)(all spatial information for the object, such as `position`. transform.position has `x` `y``z` ect. ect.) > Component (Use /ObjectName/.GetComponent) - This is 'extra's attatched t othe object - Audio sources, collision boxes, textures ect. ect. – StarshipladDev May 31 '21 at 01:59
  • @thielr7 Glad to help, best of luck! – StarshipladDev May 31 '21 at 02:00
0

It doesn't look like the TargetLocator is attached to the same GameObject as the EnemyMover.

You say yourself

On a separate object, I have a "TargetLocator" script which attempts to utilize GetComponent to find the cylinder script component when instantiated by click on a tile on the map during runtime.

Component.GetComponent looks for a component on the given Component (MonoBehaviour inherits from it) instance. In your case this -> the reference of the TargetLocator itself.

You would rather want to use e.g. FindObjectOfType which looks for the component of given type on any object in the scene Hierarchy.

target = FindObjectOfType<EnemyMover>().transform;
derHugo
  • 83,094
  • 9
  • 75
  • 115