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)
I should mention that I've attempted to:
- Reset Unity
- remove the transform and verify only the object
- Add a rigidbody to the enemy (cylinder)
- 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();
}
}
}
}