- Home /
prefab is instantiating without a script
I am instantiating a prefab but the attached script on the prefab is not attached during runtime. All other components are on the object but not the script.
the script that instantiates: public class PointerController : MonoBehaviour { public GameObject bullet; private float AngleRad; private float AngleDeg; private Vector3 mPos;
void Start()
{
mPos = new Vector3();
}
// Update is called once per frame
void Update()
{
mPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
// Get Angle in Radians
AngleRad = Mathf.Atan2(this.transform.position.y - mPos.y, this.transform.position.x - mPos.x);
// Get Angle in Degrees
AngleDeg = (180 / Mathf.PI) * AngleRad + 90;
// Rotate Object
//this.transform.rotation = Quaternion.Euler(0, 0, AngleDeg);
this.transform.rotation = Quaternion.Lerp(this.transform.rotation, Quaternion.Euler(0, 0, AngleDeg), .7f);
if (Input.GetMouseButtonDown(0))
{
GameObject go = GameObject.Instantiate(bullet, this.transform.position, this.transform.rotation) as GameObject;
}
}
}
prefab script:
public class BulletBehavior : MonoBehaviour { public float spd = 10; private Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb = this.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
rb.velocity = this.transform.forward * spd;
Debug.Log("here");
}
void OnTriggerEnter2D()
{
Destroy(this);
}
}
Probably OnTriggerEnter2D() gets called from the moment your bullet gets instatiated. You should check what the object it collides with is and start your fix from there.
void OnTriggerEnter2D(Collider2D col){
Debug.Log(col.gameObject.name);
Destroy(this); //this destroys the script, not the bullet
}
Answer by hameed-ullah-jan · Jul 16, 2019 at 07:14 AM
Check your prefab inside "Project" Menu, check if the script is attached there or not? if not then attach this script to you prefab inside "Project" menu.
I checked the prefab itself and it appears to have the script attached to it in there.
Answer by jayamohanan96 · Jun 07, 2020 at 07:43 PM
Make sure the instantiating script is not a singleton whose instance already exists in the scene. If yes then the newly instantiated object's script will be destroyed as it's instance field is already assigned.