How do I spawn allies properly?
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.
For the first script "{" is under "public class Game$$anonymous$$anager : $$anonymous$$onoBehaviour" while your other two working scripts are done like "public class Game$$anonymous$$anager : $$anonymous$$onoBehaviour {" with the "{" right next to it.
Don't know nor do I think that's the problem though. $$anonymous$$aybe it is?
@$$anonymous$$utinii That's not the problem, both ways are correct.
Your answer
Follow this Question
Related Questions
How to get the closest object in the navMesh and making the agent move towards it 1 Answer
How to spawn a navmeshagent on a certain nav mesh? 1 Answer
How do I change my NavMesh Agent from one NavMesh to another? 0 Answers
How can I change GameObject's texture? 1 Answer
NetworkServer.Spawn() only on Server (with registered prefabs) [Unity 5.2.3f1] 0 Answers