Hello, I am in a bit of a kerfuffle with this. I currently have an object that is being spawned and would like it to follow a specific set of waypoints. As it stands I can spawn the object with waypoints filled in as long as the original object is still in the scene. However, if I try to place a prefab into the spawner, the array is empty, thus causing an error.
How would I go about filling the array for the prefab once it has been spawned? I assume I could make a script that holds the waypoints and somehow get the prefab to get the points but how could this be done?
This is essentially the script that controls the prefab along with the waypoints:
public Transform[] wayPoints;
public float speed = 5.0f;
public float rotSpeed = 5.0f;
private int currentWaypoint = 0;
private CharacterController character;
private Vector3 target;
private Vector3 moveDirection;
private Quaternion _lookRotation;
private Vector3 _direction;
void Start ()
{
character = GetComponent<CharacterController>();
}
void Update ()
{
if(curHealth >=1)
{
Move ();
}
else
Die ();
}
void Move()
{
if(currentWaypoint < wayPoints.Length)
{
target = wayPoints[currentWaypoint].position;
target.y = transform.position.y; // keep waypoint at character's height
moveDirection = target - transform.position;
if(moveDirection.magnitude < 1)
{
transform.position = target; // force character to waypoint position
}
else
{
_direction = (target - transform.position).normalized;
_lookRotation = Quaternion.LookRotation(_direction);
transform.rotation = Quaternion.Slerp(transform.rotation, _lookRotation, Time.deltaTime * rotSpeed);
character.Move(moveDirection.normalized * speed * Time.deltaTime);
}
}
}
void Die()
{
Debug.Log("DEAD");
Destroy(gameObject,1.0f);
}
void OnTriggerEnter(Collider other)
{
currentWaypoint++;
}
}
Cheers