Reputation: 87
I'm making a simple game for a school project using Unity. The purpose of the game is to control a ball and pick up coins. The game has 3 scenes. I have written some code in C# to count my pick up coins and set a condition to check if all coins are picked up, if so, a wintext appears at the center of the screen.
It works just fine for the first scene (lvl1) but not for the other 2. All 3 scenes have a different number of coins. C# is new to me and I have tried various combinations but it hasn't worked.
How do I re-write this code so that the wintext appears after I pick up the right number of coins on every scene/level?
This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerController : MonoBehaviour
{
public float speed;
public Text countText;
public Text winText;
private Rigidbody rb;
private int count;
void Start()
{
rb = GetComponent<Rigidbody>();
count = 0;
SetCountText();
winText.text = "";
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(movement * speed);
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Pick Up"))
{
other.gameObject.SetActive(false);
count = count + 1;
SetCountText();
}
}
void SetCountText()
{
countText.text = "Coins: " + count.ToString();
if (count >= 2)
{
winText.text = "You Win!";
}
}
}
Upvotes: 2
Views: 145
Reputation: 640
Make a new public variable
...
public float speed;
public Text countText;
public Text winText;
public int numberOfCoinsToWin;
...
remember to set this new value in the editor for each scene
Use the variable in your condition.
if (count >= numberOfCoinstoWin)
{
winText.text = "You Win!";
}
Sounds like you're lacking a very basic understanding of C# and programming in general. Here are somethings you could research to make life easier for you:
Also using Unity to learn C# is not great. You will miss a lot of fundamentals. I suggest learning C# without unity for a week or 2 and coming back.
Upvotes: 4
Reputation: 244
This code snippet would dynamically set win condition based on scene, however it would be better if the scene could hold coinToCollect
variable.
void SetCountText()
{
countText.text = "Coins: " + count.ToString();
int coinsToCollect = 0;
switch( /* get current scene here */)
{
case "scene1": // repeat for other scenes
coinsToCollect = 2;
break;
}
if (count >= coinsToCollect)
{
winText.text = "You Win!";
}
}
Upvotes: 0