For the past couple of days I've been trying to make a simple flappy bird game. At the moment, I'm trying to write some code that will make the score go up every time the player passes through two pipes. I'm getting an error though, and I'm not too sure how to fix it. This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Score : MonoBehaviour {
public static int score = 0;
private void Start() {
score = 0;
}
private void Update() {
GetComponent<UnityEngine.UI.Text>().text = score.ToString();
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AddScore : MonoBehaviour {
private void OnTriggerEnter2D (Collider2D collision) {
Score.score ; // This is the line that's giving me errors
}
}
The exact error I'm getting is - error CS0117: 'Score' does not contain a definition for 'score'. The reason I'm a bit confused is because on Vistual Studio Code it doesn't actually show any errors. The error only appears when I try to run the game.
Any help would be greatly appreciated.
CodePudding user response:
I'm a bit bad on explaining technicalities exactly but there's always problems with changing static variables. You can create a method to add score inside the Score class for example
public void AddScore(float score)
{
this.score = score;
}
This will then work, but I would personally recommend creating an instance of the class score inside your manager for example, a score class is relatively simple and does not require the monobehaviour inheritance
CodePudding user response:
error CS0117
In simple words, it occurs when you are trying to make a reference to a member that does not exist for the data type.
In order to fix it remove the references that you are trying to make which is not defined in the base class or look inside the definition of a type to check if the member exists and use that member as a reference.
For a better understanding you can have a look at this documentation : https://support.unity.com/hc/en-us/articles/205886966-What-is-CS0117-
Also you can change the datatype from int
to float
for more accurate score. From public static int score = 0;
to public static float score = 0f;