I’m trying to create an apple projectile that will disappear if it hits a certain object. I understand that I am declaring apple as a gameobject and then trying to make it equal to a collider. I just need to know a way to make this logic work. Below are the two functions in question.
void Fire()
{
var apple = (GameObject)Instantiate (applePrefab, appleSpawn.position, appleSpawn.rotation);
apple.GetComponent<Rigidbody> ().velocity = apple.transform.forward * 10;
Destroy (apple, 5.0f);
if (apple.gameObject.CompareTag("Enemy"))
{
FireCollision (apple);
}
}
void FireCollision(Collider other)
{
other.gameObject.SetActive(false);
health = health - 5;
}
I don’t think you understand how collision is handled in Unity.
Each monobehaviour has several methods that unity tries to call through reflection.
One of these methods is: OnCollisionEnter(Collision collision)
These methods are called as soon as the monobehaviour collides with an object automatically.
You should create a script with following and put this on the applePrefab.
// Can be on the appleprefab aswel, as soon as the prefab enters the game it will destroy after 5
void Start()
{
Destroy (gameObject, 5.0f);
}
// A script on the apple prefab should contain this method
void OnCollisionEnter(Collision collision)
{
if (collision.CompareTag("Enemy"))
{
collision.gameObject.SetActive(false);
// Health must be substracted from the player I suppose?
}
}
Where your fire method will only contain:
void Fire()
{
var apple = (GameObject)Instantiate (applePrefab, appleSpawn.position, appleSpawn.rotation);
apple.GetComponent<Rigidbody> ().velocity = apple.transform.forward * 10;
}