- Home /
Why do Instantiated GameObjects Colliders only work on player i am controlling,nothing else?
I made a simple test fps game,i made a ak47 and disabled all of its colliders so it doesnt collide with other objects so it doesnt interact with anything,were gonna need that info later.
I wrote it so you can launch projectiles. It instantiates a prefab with this script attached to it: . .
public class ProjectileScript : MonoBehaviour
{
public GameObject projectileExplosion;
void Start()
{
Invoke("Explode", 20f);
}
void Update()
{
transform.Translate(Vector3.forward * Time.deltaTime);
}
private void OnCollisionEnter(Collision collision)
{
Explode();
}
void Explode()
{
Instantiate(projectileExplosion, transform.position, Quaternion.identity);
Destroy(gameObject);
}
}
. . So it invokes Explode() at start so it doesnt go on forever. Then in update it just goes forward. And on collision it calls Explode(),that simple. When i fire it,it does go forward.But it just passes thru floor,stairs,everything.Only way its gonna explode is if it touches me or if i let it go for 20s. This is how i instantiate it in gun script: . .
switch (shootsProjectiles)
{
case true:
Instantiate(projectilePrefab, transform.position, transform.rotation);
break;
case false:
break;
}
Thats it,thats all that there is to it.It passes thru ground and everything else,just when i walk into it or i get hit by it it explodes. Note: Everything in my scene is untagged and applied default layer. Pls help.
Answer by tyruji · Jul 22, 2021 at 08:29 PM
OnCollision as well as OnTrigger messages are only called when at least one of the colliding objects has a rigidbody attached. What you could do is attach a rigidbody to your bullet and make it kinematic, so it won't be affected by anything. Also you should move your bullet in FixedUpdate to make it collide without problems, and move the rigidbody instead of the transform.
example code:
private void FixedUpdate()
{
_rigidbody.MovePosition( transform.position + Vector3.forward * Time.fixedDeltaTime );
}
That should be it, good luck!
Answer by lastnoob765 · Jul 25, 2021 at 01:22 PM
I was ashamed that i didnt know that for collisions to be detected from code one of the gameObjects has to have a rigidbody.I just added rigidbody and it worked allright and i transfered my code from Update() to FixedUpdate() and now the projectile flies the same path framerate independnant.Thank you.