Hi all, I’ve been working on a game, but I can’t get my code for my collision counter to work. Does anyone have any idea how to make it work or an alternative code? Thanks
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour
{
public int scorePoint = 10;
public int MaxScore;
public Text ScoreText;
public int counter = 1;
// Use this for initialization
void Start()
{
ScoreText = GetComponent<Text>();
ScoreText.text = "" + scorePoint;
}
private void OnTriggerEnter(Collider CollisionInfo)
{
if (CollisionInfo.gameObject.tag == "AddScore")
{
Debug.Log("Collision detected");
scorePoint += 10;
}
}
}
What object is this script on? You’re calling GetComponent() which suggests that this GameObject is in a Canvas. If so, your trigger probably isn’t where you think it is.
As Madgvox says, you’ve checking for a trigger on what the script is attached to, which it looks like is your canvas objects. You need to attach a script to the object that is colliding and use that to increase the score.
I am having an error on line 18.
the error code is:
NullReferenceException: Object reference not set to an instance of an object
Score.Start () (at Assets/Score.cs:18)
You need to attach the script to the gameobject that the text component is attached to. GetComponent<> gets the component on the gameobject the script is attached to.
Say you have Canvas > TextObject in the hierarchy
Where TextObject is the UI object that has the text component is attached to, you must attach the script to TextObject.
Basically Unity works by attaching scripts to gameObjects, and calling functions on those scripts in relation to the gameObject. The OnTriggerEnter function is called when the object that the script is attached to collides with something. So you have to attach a script to some object, let’s say your player, and OnTriggerEvent will be called when your Player collides with something (assuming you have set your colliders and rigidbodies correctly). An OnTriggerEvent function attached to the canvas is useless because nothing can touch/collide with the canvas, as its part of the UI and not actually a physical object in the scene that can interact with the physics of other objects.
I’d suggest going through some of the tutorials i will link below, otherwise you will run into lots more errors like this without understanding why you are getting the errors.