I have created a cannon that fires missiles by spawning prefab missiles. when I put the Rigidbody2D.AddForce() function in the Start function of the missile, the missile will move. However, when I place the code in the Cannon script that instantiates the prefabs, it will not run.
I've been able to deduce that all code after I call Instantiate() will not run (I put some Debug.Log before and after and the ones after never get called).
Does anyone know why this is happening?
Cannon Code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cannon : MonoBehaviour
{
private bool active=false;
public Rigidbody2D missile;
public GameObject cannonOrigin;
private Animator anim;
// Start is called before the first frame update
void Start()
{
anim=gameObject.GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Space)){
active=!active;
}
if(active){
anim.Play("Cannon-Active");
}else{
anim.Play("Cannon-Deactivate");
}
if((Input.GetKeyDown(KeyCode.LeftControl)||Input.GetKeyDown(KeyCode.RightControl))&&active){
Rigidbody2D m = Instantiate(missile, cannonOrigin.transform.position, cannonOrigin.transform.rotation);
Debug.Log("Fire!");
m.AddForce(transform.forward*20);
}
}
}
Missile Prefab Code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Missile : MonoBehaviour
{
// Start is called before the first frame update
private Rigidbody2D rgbd;
public GameObject explosion;
void Start()
{
rgbd = gameObject.GetComponent<Rigidbody2D>();
//rgbd.AddForce(new Vector3(1000,0,0));
//rgbd.velocity = transform.forward*100;
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter2D(Collision2D other) {
Destroy(gameObject);
Instantiate(explosion, transform.position, Quaternion.identity);
}
}
m.AddForce() never gets called, nor does the Debug.Log() preceding it. It is as if the code block just ends after the object is instantiated. Does anyone know what is going on here?