I have a car game object with scripts that move it along a path. It works great exactly how I want it to work.
I then turn it into a prefab to spawn at a certain point on a road. I made a game controller to instantiate the prefab. It works and the car spawns where I want it to…but doesn’t move along the path. It just sits there.
When I first wrote the scripts for the game object I made it so that I had to manually drag the waypoint path object to a public variable for it to follow. And I assumed that when I made the car into a prefab it kept that variable when it spawns. It doesn’t.
So my question is how do I get my spawned car to automatically find the path to follow and actually follow?
Here is my initial code for moving the car on the path:
using UnityEngine;
using System.Collections;
public class moveOnPath : MonoBehaviour
{
public waypointPath PathToFollow;
public int CurrentWayPointID;
public float speed;
public float reachDistance;
public float rotationSpeed;
public string pathName;
Vector3 last_position;
Vector3 current_position;
void Start()
{
PathToFollow = GameObject.Find(pathName).GetComponent<waypointPath>();
last_position = transform.position;
}
void Update()
{
float distance = Vector3.Distance(PathToFollow.nodes[CurrentWayPointID].position, transform.position);
transform.position = Vector3.MoveTowards(transform.position, PathToFollow.nodes[CurrentWayPointID].position, Time.deltaTime * speed);
var rotation = Quaternion.LookRotation(PathToFollow.nodes[CurrentWayPointID].position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * rotationSpeed);
if (distance <= reachDistance)
{
CurrentWayPointID++;
}
if (CurrentWayPointID >= PathToFollow.nodes.Count)
{
CurrentWayPointID = 0;
}
}
}
And here is the code for the path:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Path : MonoBehaviour {
public Color lineColor;
public List<Transform> nodes = new List<Transform>();
void OnDrawGizmosSelected()
{
Gizmos.color = lineColor;
Transform[] pathTransforms = GetComponentsInChildren<Transform>();
nodes = new List<Transform>();
for(int i = 0; i < pathTransforms.Length; i++)
{
if(pathTransforms *!= transform)*
{
nodes.Add(pathTransforms*);*
}
}
for(int i = 0; i < nodes.Count; i++)
{
Vector3 currentNode = nodes*.position;*
Vector3 previousNode = Vector3.zero;
if (i > 0)
{
previousNode = nodes[i - 1].position;
}
else if(i == 0 && nodes.Count > 1)
{
previousNode = nodes[nodes.Count - 1].position;
}
Gizmos.DrawLine(previousNode, currentNode);
Gizmos.DrawWireSphere(currentNode, 0.3f);
}
}
}