Hello, I’m sorry to post such newbi question, but I have a problem with my OnCollisionEnter2D function
So, I have an Enemy_Grunt (a polygon sprite) and a Player (a triangle sprite). Both have a box collider 2D for testing purposes. I inserted this piece of code in my PlayerController script:
private void OnCollisionEnter2D(Collision2D col)
{
if(col.gameObject.tag == "Enemy")
{
Destroy(this.transform.gameObject);
}
}
I have my Enemy_Grunt tagged with the “Enemy” tag, and I made sure that it was spelled correctly.
I actually wonder, what did I do wrong? Can someone help me, please?
Ok, so I managed to figure it out, noob mistake to miss the Rigidbody2D. But, Now, I’m running another problem with the Projectile.
I have this function in my Player controller which makes me fire up multiple instances of the projectile: (it is being called in the FixedUpdate method)
private void Shoot()
{
if(Input.GetButtonDown("Fire1"))
{
GameObject projectilePrefab;
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
projectilePrefab = Instantiate(projectile, transform.position, Quaternion.Euler(0, 0, transform.eulerAngles.z)) as GameObject;
Rigidbody2D projectileRigidBody = projectilePrefab.AddComponent<Rigidbody2D>();
projectileRigidBody.velocity = mousePosition * projectileForce;
projectileRigidBody.gravityScale = 0.0f;
}
}
I’m getting this error:
Can't add component 'Rigidbody2D' to Projectile(Clone) because such a component is already added to the game object!
UnityEngine.GameObject:AddComponent()
PlayerController:Shoot() (at Assets/Scripts/PlayerController.cs:73)
PlayerController:FixedUpdate() (at Assets/Scripts/PlayerController.cs:25)
The line that is pointing me with the error is this one:
Rigidbody2D projectileRigidBody = projectilePrefab.AddComponent<Rigidbody2D>();
In the tutorial that I’m referencing this script of for my prototype, is working perfectly well. Someone could tell me why this is happening?
do you already have a rigidbody on the prefab?
In fact I did. I was adding 2 rigidbody2d’s at the gameobject. I’m going to set this at solved. Thank you.