Im having trouble figuring out a way to make these two functions work.
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;
}
Answer by ShadyProductions · Feb 18, 2018 at 02:23 PM
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;
}
Would it be possible to create a gameobject for my player class and associate that game object with the prefab. That would help with my health subtraction code.
You could just tag the player gameobject with 'player' and get it in code like this:
private GameObject player;
void Start()
{
player = GameObject.FindWithTag("player");
Destroy (gameObject, 5.0f);
}
Your answer
Follow this Question
Related Questions
2D Character Falling Through Ground 0 Answers
All rigidbodies fall through terrain 1 Answer
Trigger Sets GameObject 0 Answers
Trouble with Parenting gameObjects and BoxColliders 1 Answer
Detect if Raycast hits a game object 2 Answers