- Home /
I need help on a win/lose script.
I am making a pong clone, and if the ball goes off one side of the screen, it will say "You lose" but if it goes off the other, it will say "You Win"
Please write it for me, since I don't know how to script that much and this has been frustrating me for a long time.
Other things you may need to know:
I'm writing in C#
It's 3d
Position for the You Lose side: -13.89, 0, 0
Position for the You Win Side: 13.89, 0, 0
Answer by thealexguy1 · Sep 16, 2017 at 03:26 AM
Firstly, you will want to create a UI text to show the message. Right click in the hierachy and go UI -> text. Attach this script to the UI text you just made.
using UnityEngine.UI; //This is important as it allows you to edit UI elements
public Transform theBall; //This is the position of the ball, once the code is written and attached, drag the ball gameobject onto this in the Inspector
void Start(){
GetComponent<Text>().enabled = false; //Hide the text when the game starts
}
void Update(){
if (theBall.position.x >= 13.89){ //Check if the ball goes off to the right
GetComponent<Text>().enabled = true; //Show the text
GetComponent<Text>().text = "You win"; //Set the text to "You win"
Time.timeScale = 0; //Pause the game
}
else if (theBall.position.x <= -13.89){ //Check if the ball goes off to the left
GetComponent<Text>().enabled = true; //Show the text
GetComponent<Text>().text = "You lose"; //Set the text to "You lose"
Time.timeScale = 0; //Pause the game
}
}
I have not tested this but it should work... :/
Be aware that GetComponent is a bit slow, cache a reference to it in Start() or in inspector by setting it public or private with the attribute [SerializeField]
Thanks, but I keep getting an error saying "Assets/YouWinLoseScript.cs(2/7) error CS1525: Unexpected symbol 'Transform', expecting 'class', 'delegate', 'enum', 'interface', 'partial', or 'struct'"
I hardly know anything about C# so if you could help, I would be in your debt. Thanks
Hi, sorry for not clarifying, but when you make a new script, the line 'public class YouWinLoseScript : $$anonymous$$onobehaviour { }, make sure the 'using UnityEngine.UI' is above that, just underneath the 'using Unity.SystemCollections', and everything else from the 'public Transform theBall' down is all inside those main {}s, below it. If you don't understand let me know.
Your answer
Follow this Question
Related Questions
How angry bird's "GAME OVER" system work? 2 Answers
What to start with when using Unity 3? 6 Answers
Camera for 3D game Help 1 Answer
Animations not usable 2 Answers
Creating Game Objects 1 Answer