GUI does not update score

Hi

So basically i am looking to make a game where the player hits in to different coloured blocks and they get a different score from each colour, blue 10, green 20 etc. Im trying to get it so the GUI of “score” updates when the block is hit.
These is the two pieces of script that i have in an attempt to get it working.

FIRST:

public class OverallScore : MonoBehaviour 
{
    public int totalScore;
	
    void OnGUI()
    {
        GUI.Label(new Rect(10,20,100,30), "Score:" + totalScore);
    }
}

SECOND:

public class BlueBlockScore : MonoBehaviour 
{
    public int hit = 10;
	
    void OnTriggerEnter (Collider other)
    {	
        if(other.gameObject == GameObject.Find("Sphere"))
        {

            GameObject guiObj = GameObject.Find("GUIObject");
            OverallScore guiScript = (OverallScore)guiObj.GetComponent("OverallScore");
            guiScript.totalScore += hit;
        }

    }

}

So far i can get the label to appear in the top left but when i hit the blocks the score does not update and remain as zero. I should mention that the blocks are a prefab of mini cubes put together, don’t know if that makes a difference though. This is in c#

Thanks

Richard

If the expected colliding object is a prefab that you are instantiating at runtime, then it will be created with a modified name (I think Unity just adds “(clone)” to the name). You could check the modified name but I’d suggest looking into using tags instead to identify if the colliding object is what you expect - or possibly doing a GetComponent< TComponent >() if you are expecting the colliding object to have a TComponent that could identify it (although such calls are relatively expensive and I’d avoid them - on the topic: I’d also suggest you add a public reference to your BlueBlockScore of type OverallScore that you set in the inspector rather than doing a find and GetComponent call for your guiObj).

Also make sure that the collider on your target is set to a trigger. If it isn’t then the OnTriggerEnter function will not fire.

http://unity3d.com/learn/tutorials/modules/beginner/physics/colliders-as-triggers

Not sure if this would be your issue but instead of:

if(other.gameObject == GameObject.Find("Sphere"))

try

if(other.gameObject.name == "Sphere")

If you have more than one object with the name Sphere, the correct sphere might not be returned. You also should try avoiding using GameObject.Find() as much as possible. Find() will look through every object in your scene and if it is possible to do something as simple as checking the name, you should do it instead.