- Home /
Why is my collision function not calling my method inside of it?
I have a method call to another class in my collision function but for some reason it never seems to get called. I think this because my Score never changes when the collision happens. I ran the came and the collision detection does work. Does anyone know what the problem might be?
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class EnemyDie : MonoBehaviour
{
public SpaceScore sp;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
public void OnTriggerEnter(Collider other)
{
// if a pin just entered me... increase the score!
if (other.gameObject.name.Contains ("BulletPref(Clone)"))
{
Debug.Log("Enemy Collision");
Destroy(this.gameObject);
sp.setScore();
}
}
}
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class SpaceScore : MonoBehaviour
{
private int score;
Text text;
// Use this for initialization
public void init()
{
score = 0;
}
void Start ()
{
init ();
}
// Update is called once per frame
void Update ()
{
text = GetComponent<Text>();
text.text = "Score: " + score;
}
public void setScore(){
score += 10;
}
}
Answer by Alanisaac · Feb 11, 2015 at 02:51 AM
I assume in the EnemyDie
script that the public field sp
is set through the Unity editor, correct? My guess is that the field in your EnemyDie
script and the actual script attached to your Text gameobject are two different instances.
Try this. Instead of setting your sp
variable in the editor for the EnemyDie
script, do the following:
Give your Text gameobject a Tag. Let's call it "Score". You can do this in the Unity editor on the right hand side, just under where you name your object.
Modify your
EnemyDie
script to find the object with the "Score" tag in order to populate "sp". You can do that in this way:public class EnemyDie : MonoBehaviour { private SpaceScore sp; // Use this for initialization void Start () { GameObject gameObject = GameObject.FindWithTag ("Score"); sp = gameObject.GetComponent<SpaceScore>(); } // Update is called once per frame void Update () { } public void OnTriggerEnter(Collider other) { // if a pin just entered me... increase the score! if (other.gameObject.name.Contains ("BulletPref(Clone)")) { Debug.Log("Enemy Collision"); Destroy(this.gameObject); sp.setScore(); } } }
Your answer
Follow this Question
Related Questions
Can you help me about collision please ? 3 Answers
Checking if the two colliding objects have the same RGBA settings 1 Answer
Only able to jump when grounded.,Only doing something if something is true 1 Answer
Player Ship Collisions 1 Answer
Javascript score problems whilst referencing scripts. 2 Answers