I’m trying to spawn spaceship soldiers in this game I’m working in, I’ve created some scripts to test if I was correct but then I noticed that the first spawned spaceship always receive a null target and all the others behave correctly.
The scripts:
SpaceshipController.cs:
public class SpaceshipController : MonoBehaviour
{
public float spaceshipValue;
public Transform target;
private NavMeshAgent spaceship;
private const float SPEED = 3;
// Use this for initialization
void Start()
{
spaceship = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void FixedUpdate()
{
if (target != null)
{
Follow();
}
}
void Follow()
{
transform.Rotate(-90, transform.localRotation.y, transform.localRotation.z);
spaceship.SetDestination(target.position);
}
public void SetTarget(Transform target)
{
this.target = target;
}
public void SetValue(float value)
{
spaceshipValue = value;
}
public float GetValue()
{
return spaceshipValue;
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Planet")
{
Physics.IgnoreCollision(collision.gameObject.GetComponent<Collider>(), GetComponent<Collider>());
}
}
}
Planet.cs:
public class Planet : MonoBehaviour {
[SerializeField]
private float speed;
public GameObject spaceship;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
transform.Rotate(Vector3.up, speed * Time.deltaTime);
}
public void LaunchSpaceship(Transform target)
{
Instantiate(spaceship);
spaceship.GetComponent<SpaceshipController>().SetTarget(target);
spaceship.GetComponent<SpaceshipController>().SetValue(10);
}
}
GameManager.cs:
public class GameManager : MonoBehaviour {
[SerializeField] private GameObject planet1;
[SerializeField] private GameObject planet2;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update() {
if (Input.GetKeyDown(KeyCode.Space))
{
planet1.GetComponent<Planet>().LaunchSpaceship(planet2.transform);
}
}
}
Do you guys have any ideas why the first spawned spaceship always behave wrong?
P.S: English is not my mother language, so sorry for any mistakes.