Score won't reset - c#

When my player dies the score continues on and does not reset, it continues the score from the previous session. I would like to reset back to 0 once the player dies, I've added the two scripts
Score script:
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using UnityEngine;
public class ScoreScript : MonoBehaviour {
public static int scoreValue = 0;
Text score;
// Use this for initialization
void Start () {
score = GetComponent<Text>();
}
// Update is called once per frame
void Update () {
score.text = " " + scoreValue;
}
}
Player Script:
using UnityEngine;
using UnityEngine.SceneManagement;
public class Player : MonoBehaviour {
public float jumpForce = 10f;
public Rigidbody2D rb;
public SpriteRenderer sr;
public string currentColor;
public Color colorCyan;
public Color colorYellow;
public Color colorMagenta;
public Color colorPink;
void Start ()
{
SetRandomColor();
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown("Jump") || Input.GetMouseButtonDown(0))
{
rb.velocity = Vector2.up * jumpForce;
}
}
void OnTriggerEnter2D (Collider2D col)
{
if (col.tag == "ColorChanger")
{
ScoreScript.scoreValue += 1;
SetRandomColor();
Destroy(col.gameObject);
return;
}
if (col.tag != currentColor)
{
Debug.Log("GAME OVER!");
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
void SetRandomColor ()
{
int index = Random.Range(0, 4);
switch (index)
{
case 0:
currentColor = "Cyan";
sr.color = colorCyan;
break;
case 1:
currentColor = "Yellow";
sr.color = colorYellow;
break;
case 2:
currentColor = "Magenta";
sr.color = colorMagenta;
break;
case 3:
currentColor = "Pink";
sr.color = colorPink;
break;
}
}
}

It looks like scoreValue is a static variable, meaning it's maintained globally rather than per-instantiation of the ScoreScript behavior.
First off, I would change scoreValue to not be static. Then, just like you have for components such as RigidBody2D, I would add a public reference to the ScoreScript in your Player, drag that object to that field in the Unity editor, and then whenever making changes to scoreValue, use your new local reference to the ScoreScript. (So, scoreScript rather than ScoreScript).
Since like all behaviours, the ScoreScript will be reconstructed when the scene resets, this means it will then start at 0. It's not restarting right now because loading a new scene just remakes objects, it doesn't restart the entire scripting environment along with global static variables.

You need to be modifying the static variable inside of your ScoreScript whenever the conditions for death are validated in your Player component.
Judging by the source, it looks like the line:
if (col.tag != currentColor)
denotes the end of a game. If this is the case, you'll want to reference ScoreScript.score after the if statement and set the value of this static variable to 0 to reset the score upon death.

Related

Show Time as highest score when game over Unity script

I need help with my script. I really can't understand how to make it. I have a script that counts time but I don't know how to make it so that when the game is over the time appears in my Game Over scene as the highest score. I only need to save this high score for one time. After the game is closed the score can be removed. In the game, I have a countdown timer, when it reaches 0 the game is over.
This is my TimeCounter script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TimeCounter: MonoBehaviour
{
public Text timerText;
private float startTime;
bool finishCountTime = false;
public string minutes, seconds;
// Use this for initialization
void Start()
{
}
public void startTheTimer()
{
Invoke("startTime", 10);
startTime = Time.time;
}
public void stopTheTimer()
{
finishCountTime = true;
}
// Update is called once per frame
void Update()
{
float t = Time.time - startTime;
minutes = ((int)t / 60).ToString();
seconds = (t % 60).ToString("f2");
timerText.text = minutes + ":" + seconds;
}
}
and this is GameManager script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Threading;
public class GameManager: MonoBehaviour
{
[SerializeField] private float timer = 30;
private void Awake()
{
pop.onClicked += PopClicked;
}
private void OnDestroy()
{
pop.onClicked -= PopClicked;
}
private void PopClicked()
{
if (pop.Unclicked.Count == 0)
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
}
private void Update()
{
if (timer <= 0)
{
SceneManager.LoadScene("GameOver");
}
}
}
Here is an example snippet of how to use DontDestroyOnLoad along with the SceneLoaded delegates.
using UnityEngine;
using UnityEngine.SceneManagement;
public class ExampleScript : MonoBehaviour
{
private float score;
private void Awake()
{
var objs = FindObjectsOfType(typeof(ExampleScript));
if (objs.Length > 1)
{
Destroy(this.gameObject);
}
DontDestroyOnLoad(this.gameObject);
}
private void OnEnable()
{
SceneManager.sceneLoaded += OnSceneLoaded;
}
private void OnDisable()
{
SceneManager.sceneLoaded -= OnSceneLoaded;
}
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
if(scene.name == "gameOver")
{
// display the time here as we are showing the score
Debug.Log(score);
}
else
{
// we loaded into another scene - presumably your game scene, so reset the score
score = 0;
}
}
}
As it is DontDestroyOnLoad, you will need to check if the current scene contains the object already and destroy it. As you have two scripts running your logic, you might need to slightly tweak it so that one of the managers is able to communicate to one another to pull your score or move it to the same script. I have greatly over-generalized your issue as I was not sure which part you did not understand.
Edit: Here is the more in-depth answer on how to achieve what you would like to do.
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class TestScript : MonoBehaviour
{
private float score; // our current score
private bool updateScore = false; // whether or not we should update our score UI every frame
private Text ScoreText = null; // our text object that updates our score
private void Awake()
{
// as the object is DontDestroyOnLoad, we need to check if another instance exists
// if one does, we need to delete it as if multiple exist in one scene, there could be issues
// if a player continually replays your scene where this object starts, then multiple will exist
var objs = FindObjectsOfType(typeof(TestScript));
if (objs.Length > 1)
{
Destroy(this.gameObject);
}
DontDestroyOnLoad(this.gameObject);
}
private void OnEnable()
{
// add the callback for when a scene is loaded
SceneManager.sceneLoaded += OnSceneLoaded;
}
private void OnDisable()
{
// remove the callback from when a scene is loaded
SceneManager.sceneLoaded -= OnSceneLoaded;
}
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
// grab the new reference to out score UI
ScoreText = GameObject.Find("Score").GetComponent<Text>();
// when we have the gameover scene, display our final score
if (scene.name == "gameover")
{
// display the time here as we are showing the score
ScoreText.text = "Final Score: " + score.ToString("#");
updateScore = false;
}
else
{
// we loaded into another scene - presumably your game scene, so reset the score
score = 0;
updateScore = true;
}
}
private void Update()
{
// if we are in the game scene and we should update score, update the score however you like
if(updateScore)
{
score += Time.deltaTime;
ScoreText.text = "Current Score: " + score.ToString("#");
}
// this is here solely for testing - instead of a real game just hit space to end the game and restart it
if(Input.GetKeyDown(KeyCode.Space))
{
if(SceneManager.GetActiveScene().name == "gameover")
{
SceneManager.LoadScene(0);
}
else
{
SceneManager.LoadScene("gameover");
}
}
}
}
Here is an example of the script working as well as the two scene hierarchies. For this to work exactly as I have it, you will need two scenes. In your build settings, the first scene will be your game scene, and then there needs to be some other scene in the build settings with the name gameover. As well, you will need to have some sort of UnityEngine.UI.Text component that is called Score in both scenes.
All of this can be changed, but this is what you need to do to get it to work as I have it set up.

Unity3D playing sound when Player collides with an object with a specific tag

I using Unity 2019.2.14f1 to create a simple 3D game.
In that game, I want to play a sound anytime my Player collides with a gameObject with a specific tag.
The MainCamera has an Audio Listener and I am using Cinemachine Free Look, that is following my avatar, inside the ThridPersonController (I am using the one that comes on Standard Assets - but I have hidden Ethan and added my own character/avatar).
The gameObject with the tag that I want to destroy has an Audio Source:
In order to make the sound playing on the collision, I started by creating an empty gameObject to serve as the AudioManager, and added a new component (C# script) to it:
using UnityEngine.Audio;
using System;
using UnityEngine;
public class AudioManager : MonoBehaviour
{
public Sound[] sounds;
// Start is called before the first frame update
void Awake()
{
foreach (Sound s in sounds)
{
s.source = gameObject.AddComponent<AudioSource>();
s.source.clip = s.clip;
s.source.volume = s.volume;
s.source.pitch = s.pitch;
}
}
// Update is called once per frame
public void Play (string name)
{
Sound s = Array.Find(sounds, sound => sound.name == name);
s.source.Play();
}
}
And created the script Sound.cs:
using UnityEngine.Audio;
using UnityEngine;
[System.Serializable]
public class Sound
{
public string name;
public AudioClip clip;
[Range(0f, 1f)]
public float volume;
[Range(.1f, 3f)]
public float pitch;
[HideInInspector]
public AudioSource source;
}
After that, in the Unity UI, I went to the Inspector in the gameObject AudioManager, and added a new element in the script that I named: CatchingPresent.
On the Third Person Character script, in order to destroy a gameObject (with a specific tag) when colliding with it, I have added the following:
void OnCollisionEnter(Collision other)
{
if (other.gameObject.CompareTag("Present"))
{
Destroy(other.gameObject);
count = count - 1;
SetCountText();
}
}
It is working properly as that specific object is disappearing on collision. Now, in order to play the sound "CatchingPresent" anytime the Player collides with the object with the tag, in this case, Present, I have tried adding the following to the if in the OnCollisionEnter:
FindObjectOfType<AudioManager>().Play("CatchingPresent");
But I get the error:
The type or namespace name 'AudioManager' could not be found (are you
missing a using directive or an assembly reference?)
AudioManager.instance.Play("CatchingPresent");
But I get the error:
The name 'AudioManager' does not exist in the current context
As all the compiler errors need to be fixed before entering the Playmode, any guidance on how to make the sound playing after a collision between the player and the gameObject with the tag Present is appreciated.
Edit 1: Assuming that it is helpful, here it goes the full ThirdPersonUserControl.cs:
using System;
using UnityEngine;
using UnityEngine.UI;
using UnityStandardAssets.CrossPlatformInput;
namespace UnityStandardAssets.Characters.ThirdPerson
{
[RequireComponent(typeof (ThirdPersonCharacter))]
public class ThirdPersonUserControl : MonoBehaviour
{
public Text countText;
public Text winText;
private int count;
private ThirdPersonCharacter m_Character; // A reference to the ThirdPersonCharacter on the object
private Transform m_Cam; // A reference to the main camera in the scenes transform
private Vector3 m_CamForward; // The current forward direction of the camera
private Vector3 m_Move;
private bool m_Jump; // the world-relative desired move direction, calculated from the camForward and user input.
private void Start()
{
count = 20;
SetCountText();
winText.text = "";
// get the transform of the main camera
if (Camera.main != null)
{
m_Cam = Camera.main.transform;
}
else
{
Debug.LogWarning(
"Warning: no main camera found. Third person character needs a Camera tagged \"MainCamera\", for camera-relative controls.", gameObject);
// we use self-relative controls in this case, which probably isn't what the user wants, but hey, we warned them!
}
// get the third person character ( this should never be null due to require component )
m_Character = GetComponent<ThirdPersonCharacter>();
}
private void Update()
{
if (!m_Jump)
{
m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
}
}
// Fixed update is called in sync with physics
private void FixedUpdate()
{
// read inputs
float h = CrossPlatformInputManager.GetAxis("Horizontal");
float v = CrossPlatformInputManager.GetAxis("Vertical");
bool crouch = Input.GetKey(KeyCode.C);
// calculate move direction to pass to character
if (m_Cam != null)
{
// calculate camera relative direction to move:
m_CamForward = Vector3.Scale(m_Cam.forward, new Vector3(1, 0, 1)).normalized;
m_Move = v*m_CamForward + h*m_Cam.right;
}
else
{
// we use world-relative directions in the case of no main camera
m_Move = v*Vector3.forward + h*Vector3.right;
}
#if !MOBILE_INPUT
// walk speed multiplier
if (Input.GetKey(KeyCode.LeftShift)) m_Move *= 0.5f;
#endif
// pass all parameters to the character control script
m_Character.Move(m_Move, crouch, m_Jump);
m_Jump = false;
}
void OnCollisionEnter(Collision other)
{
if (other.gameObject.CompareTag("Present"))
{
Destroy(other.gameObject);
count = count - 1;
SetCountText();
//FindObjectOfType<AudioManager>().Play("CatchingPresent");
AudioManager.instance.Play("CatchingPresent");
}
}
void SetCountText()
{
countText.text = "Missing: " + count.ToString();
if (count == 0)
{
winText.text = "You saved Christmas!";
}
}
}
}
Edit 2: Hierarchy in Unity:
Reformulated the approach that I was following and solved the problem by simply adding an Audio Source to the ThirdPersonController (with the AudioClip that I wanted to call) and added GetComponent<AudioSource>().Play(); to the if statement as it follows:
void OnCollisionEnter(Collision other)
{
if (other.gameObject.CompareTag("Present"))
{
Destroy(other.gameObject);
count = count - 1;
SetCountText();
GetComponent<AudioSource>().Play();
}
}
Importing your scripts myself works without any issues when using FindObjectOfType<AudioManager>().Play("CatchingPresent");. Try reimporting your scripts from the editor (right click in the project folder > reimport all. this might take a while depending on the size of your project)
to use AudioManager.instance.Play("CatchingPresent"); you would first need to create a static variable that holds instance like this (this only works as a singleton, and will break if multiple AudioManager's are in the scene):
public class AudioManager : MonoBehaviour
{
//Create a static AudioManager that will hold the reference to this instance of AudioManager
public static AudioManager Instance;
public Sound[] sounds;
//Assign Instance to the instance of this AudioManager in the constructor
AudioManager()
{
Instance = this;
}
// Rest of the AudioManager code
}
Doing it like this, and using the rest of your code also works for me.

How can I reference back to objects/components of a parent object after destroyed it and re instantiated?

I have in the Hierarchy one scene and 3 parent objects. The 3 parent objects are :
Game Data (Where all the gameplay objects are childs of it)
Main Menu
Game Manager (That control on pausing/unpausing the game in some cases)
The idea the main goal is when the game start it's starting with the main menu then when clicking the start new game button it will start the game when hit the escape key it will be back to the main menu and again I can start a new game or resuming the game. I also did that while the game is running if you hit the P button it will pause/unpause the game.
First the script that is attached to the Game Manager :
Here I'm doing a reference for the Dialogue System, Depth Of Field, Main Menu And in the bottom I'm using find to find back the Depth Of Field and the Dialogue System since I'm destroying the Game Data object when starting a new game :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameController : MonoBehaviour
{
public GameObject dialogueSystem;
public DepthOfField depthOfField;
public static bool gamepaused = false;
public GameObject mainMenu;
private void Start()
{
Time.timeScale = 0f;
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.P))
{
gamepaused = !gamepaused;
if (gamepaused)
{
Time.timeScale = 0f;
}
else
{
Time.timeScale = 1f;
}
}
if (Input.GetKeyDown(KeyCode.Escape))
{
if(depthOfField == null || dialogueSystem == null)
{
depthOfField = GameObject.Find("Player Camera").GetComponent<DepthOfField>();
dialogueSystem = GameObject.Find("Dialogue System");
}
depthOfField.DepthOfFieldInit(3f);
Time.timeScale = 0f;
dialogueSystem.SetActive(false);
mainMenu.SetActive(true);
Cursor.visible = true;
Cursor.lockState = CursorLockMode.None;
}
}
}
The problem is that the Dialogue System and Depth Of Field are in the Game Data and when I destroy the Game Data and instantiate the Game Data using a prefab over again to make a new game to start the variables in the GameController script lost reference and I need to use find. But using find so many times is a good idea ?
This script the next one is attached to the Main Menu :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainMenu : MonoBehaviour
{
public GameObject gameDataPrefab;
public GameObject gameData;
public GameObject mainMenu;
public void StartNewGame()
{
var gdata = GameObject.Find("Game Data");
if (gdata != null)
{
Destroy(gdata);
}
GameObject go = Instantiate(gameDataPrefab);
go.name = "Game Data";
mainMenu.SetActive(false);
GameController.gamepaused = false;
Time.timeScale = 1f;
}
public void ResumeGame()
{
}
public void QuitGame()
{
Application.Quit();
}
}
Here when I click the UI button to start a new game in the function StartNewGame I destroy the Game Data and create a new one. This make the variables in the GameController script to lost references.
The last script is attached to the Game Data this script I'm calling the method DepthOfFieldInit to make effect when I hit the escape key back to the Main Menu.
The problem is that some variables are lost references since the Game Data is destroyed. For example I'm getting null on :
playerLockMode.PlayerLockState(true, true);
Since playerLockMode is also on the Game Data that have been destroyed.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.PostProcessing;
public class DepthOfField : MonoBehaviour
{
public UnityEngine.GameObject player;
public PostProcessingProfile postProcessingProfile;
public bool dephOfFieldFinished = false;
public LockSystem playerLockMode;
private Animator playerAnimator;
private float clipLength;
private Coroutine depthOfFieldRoutineRef;
// Start is called before the first frame update
void Start()
{
if (depthOfFieldRoutineRef != null)
{
StopCoroutine(depthOfFieldRoutineRef);
}
playerAnimator = player.GetComponent<Animator>();
AnimationClip[] clips = playerAnimator.runtimeAnimatorController.animationClips;
foreach (AnimationClip clip in clips)
{
clipLength = clip.length;
}
DepthOfFieldInit(clipLength);
// Don't forget to set depthOfFieldRoutineRef to null again at the end of routine!
}
public void DepthOfFieldInit(float duration)
{
var depthOfField = postProcessingProfile.depthOfField.settings;
depthOfField.focalLength = 300;
StartCoroutine(changeValueOverTime(depthOfField.focalLength, 1, duration));
postProcessingProfile.depthOfField.settings = depthOfField;
}
public IEnumerator changeValueOverTime(float fromVal, float toVal, float duration)
{
playerLockMode.PlayerLockState(true, true);
float counter = 0f;
while (counter < duration)
{
var dof = postProcessingProfile.depthOfField.settings;
counter += Time.deltaTime;
float val = Mathf.Lerp(fromVal, toVal, counter / duration);
dof.focalLength = val;
postProcessingProfile.depthOfField.settings = dof;
yield return null;
}
playerAnimator.enabled = false;
dephOfFieldFinished = true;
depthOfFieldRoutineRef = null;
}
}
But I don't understand if I instantiate right away back the Game Data when starting a new game why the variables lost references ? And is there a better way to use Find at any place many times after the Game Data have been destroyed ? And maybe the whole code in the StartNewGame is wrong ?
My main goal is when clicking the StartNewGame start over a new game. When hit the escape key pause the game and go back to the main menu.
Here is a screenshot of my Hierarchy :

Changing data on click button

I have some functionalities within some GameObjects.
These functionalities need to be changed when an upgrade is purchased within the game. The problem is that each function is set on its own object.
The first problem is that the variables don't change when I click on the button. As you can see I have added an onclick value to the button, stating that when the button is clicked. The value should change.
The problem here is that "Object reference not set to an instance"
The second problem I face is that each projectile is fired independently. So if I change the static damage of 1 it won't be transferred to other projectiles.
UpgradeMenu
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UpgradeMenu : MonoBehaviour
{
[SerializeField]
private Text accuracyText;
[SerializeField]
private Text speedText;
[SerializeField]
private Text damageText;
[SerializeField]
private float accuracyMultiplier = 0.7f;
private Weapon weapon;
private Projectile projectile;
private Player player;
void OnEnable()
{
UpdateValues();
}
void UpdateValues ()
{
accuracyText.text = weapon.randomAngle.ToString();
damageText.text = projectile.DamageOnHit.ToString();
speedText.text = player.MaxRun.ToString();
}
public void UpgradeAccuracy ()
{
weapon.randomAngle = (int)weapon.randomAngle * accuracyMultiplier;
UpdateValues();
}
public void UpgradeDamage ()
{
projectile.DamageOnHit = (int)projectile.DamageOnHit + 1;
UpdateValues();
}
}
Projectile (DamageScript)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//[RequireComponent (typeof(Rigidbody2D))]
public class Projectile : MonoBehaviour {
[Header ("Speed")]
public float baseSpeed;
public float randomSpeed;
public Vector2 SpeedV2;
public Vector2 Direction;
[Header ("Damage")]
public int DamageOnHit;
[Header ("Layers")]
public LayerMask solid_layer;
public LayerMask entities_layer;
[Header ("OnHit FX")]
public GameObject HitFxPrefab;
public GameObject DustFxPrefab;
[Header ("Bounce")]
public bool BounceOnCollide = false;
public int bouncesLeft = 0;
[HideInInspector]
public Health owner; // owner of the projectile
private Vector2 Position; // Current position
private Vector2 movementCounter = Vector2.zero; // Counter for subpixel movement
public BoxCollider2D myCollider;
List<Health> healthsDamaged = new List<Health>(); // List to store healths damaged
void OnCollideWith (Collider2D col, bool horizontalCol = true) {
var component = col.GetComponent<Health> ();
// If the target the hitbox collided with has a health component and it is not our owner and it is not on the already on the list of healths damaged by the current hitbox
if (component != null && component != owner && !healthsDamaged.Contains(component)) {
// Add the health component to the list of damaged healths
healthsDamaged.Add (component);
// Apply the damage
var didDamage = component.TakeDamage (DamageOnHit);
// Destroy the projectile after applying damage
if (didDamage) {
DestroyMe ();
return;
}
}
// if the projectile hit's a solid object, destroy it
if (col.gameObject.layer == (int)Mathf.Log(solid_layer.value, 2)) {
DestroyMeWall ();
return;
}
}
void OnCollideWithEntity(Collider2D col) {
var component = col.GetComponent<Health> ();
// If the target the hitbox collided with has a health component and it is not our owner and it is not on the already on the list of healths damaged by the current hitbox
if (component != null && component != owner && !healthsDamaged.Contains(component)) {
// Add the health component to the list of damaged healths
healthsDamaged.Add (component);
// Apply the damage
var didDamage = component.TakeDamage (DamageOnHit);
// Destroy the projectile after applying damage
if (didDamage) {
DestroyMe ();
}
}
}
First of all, change
[Header ("Damage")]
public int DamageOnHit;
to static
public static int DamageOnHit = /*your starting value*/;
This ensures that all projectiles will share the same damage it deals on a hit.
For instance, if you currently have 10 projectiles in a scene, and DamageOnHit is 2, they all will deal 2 damage.
Without the static, each of the projectile will have it's own DamageOnHit. This brings us to the next case too:
If each projectile had it's own DamageOnHit, and we want to modify DamageOnHit, we need to specify which projectile's damage to modify.
But if it's static, it becomes much simpler as ALL of the projectile shares the same DamageOnHit.
Now, if you wanted to change the DamageOnHit for ALL projectiles, just do
Projectile.DamageOnHit = /*Your new damage value*/
Also, your null reference exception occured due to the fact that you never did assign your projectile in UpgradeMenu.
(Notice how you never did projectile = /*your projectile*/ in UpgradeMenu.cs?)
By default, that will make the variable null. And trying to do null.DamageOnHit += 1 would make no sense.
Small Edit: Making a variable static would also mean that you can't expose it to the inspector. But you can assign a starting value like the code shown initially.

Text does not update in Unity C#

I'm designing a game for my project and somehow the score(text) does not update after an action. It stuck at 0.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class uiManager : MonoBehaviour {
public Text scoreText;
bool gameOver;
int score;
// Use this for initialization
void Start () {
gameOver = false;
score = 0;
InvokeRepeating ("scoreUpdate", 1.0f, 0.5f);
}
// Update is called once per frame
void Update ()
{
scoreText.text = "Point: " + score;
}
void scoreUpdate()
{
if (gameOver == false)
{
score += 1;
}
}
public void gameOVER()
{
gameOver = true;
}
public void Play()
{
Application.LoadLevel ("MuachiJump");
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "branch")
{
score += 1;
Destroy(col.gameObject);
}
}
I just want to make sure is there any mistake in this code? All of them seem to be correct.
The code by itself seems fine. Make sure that uiManager is attached to an object in your scene that is active. In the Update method, if you add, for example, Debug.Log(score), it should print to the log every frame. If this isn't happening, you need to attach the script to an object in your scene as well as make sure that the Text object has a valid reference.
Do you have an active object with the script attached on your scene?
In my case the size of the textbox was the issue, just enlarge it and your score will be visible.

Categories