I'm making my own game in Unity 4.6. I have background music playing all the time. But i want to give my players the possibility to mute the music with a simple toggle.
I'm using C#. Anyone any ideas on how to do this?
Would be a great help!
this is how i solved it!
using UnityEngine;
using System.Collections;
public class Mute: MonoBehaviour{
bool isMute;
public void MusicMute (){
if(isMute == true){
Debug.Log("Music On");
AudioListener.volume = 1;
isMute = false;
}
else {
Debug.Log("Music Off");
isMute = true;
AudioListener.volume = 0;
}
}
}
Imagining that you are using a GUI Button to toggle...
You can toggle the volume by following:
void OnGUI ()
{
if (GUI.Button (new Rect (0, 0, 30, 30), "Music")) {
if (audio.volume != 0) {
audio.volume = 0;
} else {
audio.volume = 1; //or whatever value you want
}
}
}
Otherwise you can play or stop by following:
void OnGUI ()
{
if (GUI.Button (new Rect (0, 0, 30, 30), "Music")) {
if (audio.isPlaying) {
audio.Stop ();
} else {
audio.Play ();
}
}
}
Hope it helps.
Related
we have a dash button in the game. If we press the button dash button is working well but the problem is if we press anywhere on screen it is working too! We only want to work that function with button.
Anyone help us please?
Code:
public void Dash()
{
if (Input.GetMouseButtonDown(0))
{
activeMoveSpeed = dashSpeed;
dashCounter = dashLength;
}
if (dashCounter > 0)
{
canShoot = false;
dashCounter -= Time.deltaTime;
if (dashCounter <= 0)
{
canShoot = false;
activeMoveSpeed = speed;
dashCoolCounter = dashCoolDown;
}
}
if (dashCoolCounter > 0)
{
canShoot = false;
dashCoolCounter -= Time.deltaTime;
}
}
private void FixedUpdate()
{
Movement();
Dash();
}
Button and Game
Button
The function you specify in OnClick will be called whenever the button is clicked.
Currently, you are not using the button at all. I think you meant something like this (StartDash() is the function that should be chosen in OnClick):
public void StartDash()
{
activeMoveSpeed = dashSpeed;
dashCounter = dashLength;
}
private void DoDash()
{
if (dashCounter > 0)
{
canShoot = false;
dashCounter -= Time.deltaTime;
if (dashCounter <= 0)
{
canShoot = false;
activeMoveSpeed = speed;
dashCoolCounter = dashCoolDown;
}
}
if (dashCoolCounter > 0)
{
canShoot = false;
dashCoolCounter -= Time.deltaTime;
}
}
private void FixedUpdate()
{
Movement();
DoDash();
}
Take a look at the related pages in the Unity Documentation:
Manual - Button
Scripting - UI.Button
Scripting - UI.Button.onclick
using UnityEngine.UI;
using UnityEngine;
public class Tutorial : MonoBehaviour
{
public Text tutorialText;
void Update()
{
tutorialText.text = "Press [SPACE] to Jump... (obviously...)";
if (Input.GetKeyDown(KeyCode.Space))
{
while (true)
{
tutorialText.text = "Now Shoot";
if (Input.GetKeyDown(KeyCode.Mouse0))
{
while (true)
{
tutorialText.text = "Nice";
}
}
}
}
}
}
Change your code to that, because right now you are in a infinite loop which sets your tutorialtext to "Now Shoot" again and again until Unity crashes.
if (Input.GetKeyDown(KeyCode.Space))
{
tutorialText.text = "Now Shoot";
}
else if (Input.GetKeyDown(KeyCode.Mouse0))
{
tutorialText.text = "Nice";
}
If you want the text to disappear after the first time you done the actions you should add bool variables.
bool jumped = false;
bool hasShot = false;
And then implement thoose bools into your code like this:
if (Input.GetKeyDown(KeyCode.Space))
{
if (jumped)
return;
tutorialText.text = "Now Shoot";
jumped = true;
}
else if (Input.GetKeyDown(KeyCode.Mouse0))
{
if (hasShot || !jumped)
return;
tutorialText.text = "Nice";
hasShot = true;
}
You also need to move the first text definition out of Update, because Update is called each frame. Put it into void Start() instead
void Start() {
tutorialText.text = "Press [SPACE] to Jump... (obviously...)";
}
I made the game in Unity Space Shooter. In my Space shooter there is 2 button it work for Left and Right moving. I want when we touch the left button player go to left only in Single Touch same like Right Button also.
This , are the some codes which i used in Game. Please Help me out from this.
TouchControl.cs
using UnityEngine;
using System.Collections;
public class TouchControl : MonoBehaviour {
public GUITexture moveLeft;
public GUITexture moveRight;
public GUITexture fire;
public GameObject player;
private PlayerMovement playerMove;
private Weapon[] weapons;
void Start()
{
playerMove = player.GetComponent<PlayerMovement> ();
}
void CallFire()
{
weapons = player.GetComponentsInChildren<Weapon> ();
foreach (Weapon weapon in weapons) {
if(weapon.enabled == true)
weapon.Fire();
}
}
void Update()
{
// int i = 0;
if(Input.touchCount > 0)
{
for(int i =0; i < Input.touchCount; i++)
{
// if(moveLeft.HitTest(Input.GetTouch(i).position, Camera.main))
// {
// if(Input.touchCount > 0)
// {
// playerMove.MoveLeft();
// }
// }
// if(moveRight.HitTest(Input.GetTouch(i).position, Camera.main))
// {
// if(Input.touchCount > 0)
// {
// playerMove.MoveRight();
// }
// }
// if(moveLeft.HitTest(Input.GetTouch(i).position, Camera.main))
// {
// if(Input.touchCount > 0)
// {
// CallFire();
// }
// }
// Touch t = Input.GetTouch(i);
Touch t = Input.GetTouch (i);
Input.multiTouchEnabled = true;
if(t.phase == TouchPhase.Began || t.phase == TouchPhase.Stationary)
{
if(moveLeft.HitTest(t.position, Camera.main))
{
playerMove.MoveLeft ();
}
if(moveRight.HitTest(t.position, Camera.main))
{
playerMove.MoveRight();
}
}
if(t.phase == TouchPhase.Began)
{
if(fire.HitTest(t.position, Camera.main))
{
CallFire();
}
}
if(t.phase == TouchPhase.Ended)
{
}
}
}
}
}
PlayerMovement.cs
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
public float speedMove = 6.0f;
public float bonusTime;
private bool toLeft = false;
private bool toRight = false;
public GameObject shield;
public GUIText bonustimeText;
private bool counting = false;
private float counter;
private Weapon[] addWeapons;
public Sprite strongShip;
public Sprite normalSprite;
public Sprite shieldSprite;
private SpriteRenderer sRender;
private Weapon weaponScript;
void Start () {
counter = bonusTime;
sRender = GetComponent<SpriteRenderer> ();
addWeapons = GetComponentsInChildren<Weapon> ();
foreach (Weapon addWeapon in addWeapons) {
addWeapon.enabled = false;
}
weaponScript = GetComponent<Weapon>();
weaponScript.enabled = true;
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.A)) {
toLeft = true;
}
if (Input.GetKeyUp (KeyCode.A)) {
toLeft = false;
}
if (Input.GetKeyDown (KeyCode.D)) {
toRight = true;
}
if (Input.GetKeyUp (KeyCode.D)) {
toRight = false;
}
if (counting) {
counter -= Time.deltaTime;
bonustimeText.text = counter.ToString("#0.0");
}
}
void FixedUpdate()
{
if (toLeft) {
MoveLeft();
}
if (toRight) {
MoveRight();
}
}
public void MoveLeft()
{
transform.Translate(Vector2.right * -speedMove* Time.deltaTime);
}
public void MoveRight()
{
transform.Translate(Vector2.right * speedMove * Time.deltaTime);
}
void OnCollisionEnter2D(Collision2D coll)
{
if (coll.gameObject.tag == "StrongMode") {
Destroy (coll.gameObject);
counting = true;
StrongMode();
Invoke ("Downgrade", bonusTime);
}
if (coll.gameObject.tag == "ShieldMode") {
Destroy (coll.gameObject);
counting = true;
ShieldMode();
Invoke("Downgrade", bonusTime);
}
if (coll.gameObject.tag == "Life") {
GUIHealth gui = GameObject.Find ("GUI").GetComponent<GUIHealth> ();
gui.AddHealth();
SendMessage("AddHp");
SoundHelper.instanceSound.PickUpSound();
Destroy(coll.gameObject);
}
if (coll.gameObject.tag == "Enemy") {
SendMessage("Dead");
}
}
void Downgrade()
{
SoundHelper.instanceSound.BonusDownSound ();
counting = false;
bonustimeText.text = "";
counter = bonusTime;
sRender.sprite = normalSprite;
weaponScript.enabled = true;
foreach (Weapon addWeapon in addWeapons) {
addWeapon.enabled = false;
}
weaponScript.enabled = true;
shield.SetActive (false);
}
void StrongMode()
{
SoundHelper.instanceSound.BonusUpSound ();
sRender.sprite = strongShip;
foreach (Weapon addWeapon in addWeapons) {
addWeapon.enabled = true;
}
weaponScript.enabled = false;
}
void ShieldMode()
{
SoundHelper.instanceSound.BonusUpSound ();
sRender.sprite = shieldSprite;
shield.SetActive (true);
}
// void OnDestroy()
// {
// bonustimeText.text = "";
// }
}
In the Player Controller script Create:
public Vector3 playerDirection = Vector3.zero;
Then in touch control instead of:
if (moveLeft.HitTest(Input.GetTouch(i).position, Camera.main))
{
if (Input.touchCount > 0)
{
playerMove.MoveLeft();
}
}
if (moveRight.HitTest(Input.GetTouch(i).position, Camera.main))
{
if (Input.touchCount > 0)
{
playerMove.MoveRight();
}
}
Use:
if (moveLeft.HitTest(Input.GetTouch(i).position, Camera.main))
{
if (Input.touchCount > 0)
{
playerMove.playerDirection = Vector3.left;
}
}
if (moveRight.HitTest(Input.GetTouch(i).position, Camera.main))
{
if (Input.touchCount > 0)
{
playerMove.playerDirection = Vector3.right;
}
}
Then in the Update method of Player Controller use:
transform.Translate(playerDirection * speedMove * Time.deltaTime);
public class PlayerController {
public EPlayerState playerState = EPLayerState.Idle;
void Update () {
// If click right button
playerState = EPlayerState.MoveRight;
// Else if click left button
playerState = EPlayerState.MoveLeft
if (playerState == EPlayerState.MoveRight)
// Move player right;
if (playerState == EPlayerState.MoveLeft
// Move player right;
}
}
public enum EPlayerState {
Idle,
MoveRight,
MoveLeft
}
You can also use something like a boolean called isRight, move right when it's true and left when it's false. Then when you click left or right button just change the variable.
`using UnityEngine;
public class HalfScreenTouchMovement : MonoBehaviour
{
private float screenCenterX;
private void Start()
{
// save the horizontal center of the screen
screenCenterX = Screen.width * 0.5f;
}
private void Update()
{
// if there are any touches currently
if(Input.touchCount > 0)
{
// get the first one
Touch firstTouch = Input.GetTouch(0);
// if it began this frame
if(firstTouch.phase == TouchPhase.Began)
{
if(firstTouch.position.x > screenCenterX)
{
// if the touch position is to the right of center
// move right
}
else if(firstTouch.position.x < screenCenterX)
{
// if the touch position is to the left of center
// move left
}
}
}
}
}`
May be helpfull
create script. for example player.cs
public class PlayerController : MonoBehaviour
{
bool swipeRight = false;
bool swipeLeft = false;
bool touchBlock = true;
bool canTouchRight = true;
bool canTouchLeft = true;
void Update()
{
swipeLeft = Input.GetKeyDown("a") || Input.GetKeyDown(KeyCode.LeftArrow);
swipeRight = Input.GetKeyDown("d") || Input.GetKeyDown(KeyCode.RightArrow);
TouchControl();
if(swipeRight) //rightMove logic
else if(swipeLeft) //leftMove logic
}
void TouchControl()
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved && touchBlock == true)
{
touchBlock = false;
// Get movement of the finger since last frame
var touchDeltaPosition = Input.GetTouch(0).deltaPosition;
Debug.Log("touchDeltaPosition "+touchDeltaPosition);
if(touchDeltaPosition.x > 0 && canTouchRight == true)
{
//rightMove
swipeRight = true; canTouchRight = false;
Invoke("DisableSwipeRight",0.2f);
}
else if(touchDeltaPosition.x < 0 && canTouchLeft == true)
{
//leftMove
swipeLeft = true; canTouchLeft = false;
Invoke("DisableSwipeLeft",0.2f);
}
}
}
void DisableSwipeLeft()
{
swipeLeft = false;
touchBlock = true;
canTouchLeft = true;
}
void DisableSwipeRight()
{
swipeRight = false;
touchBlock = true;
canTouchRight = true;
}
}
Whenever I press escape button,my game paused and gui shows but my health bar at canvas does not pause.. here is my code.. any suggestions
using UnityEngine;
using System.Collections;
public class PauseMenu : MonoBehaviour {
bool paused = false;
void Update()
{
if(Input.GetButtonDown("pauseButton"))
paused = togglePause();
}
void OnGUI()
{
if(paused)
{
if(GUI.Button(new Rect(Screen.width/2- 100,Screen.height/2+1,180,40),"Resume Game"))
paused = togglePause();
}
}
bool togglePause()
{
if(Time.timeScale == 0f)
{
Time.timeScale = 1f;
return(false);
}
else
{
Time.timeScale = 0f;
return(true);
}
}
}
Time.timeScale = 0 doesn't stop everything.
If it would stop everything your game would freeze and be completly unresponsive. If your damaging is called e.g. in Update and doesn't use Time.deltaTime it will still be called.
I'm failing to understand how to decouple business logic of a controller and view for Unity3D GUI controls.
For example, if I have a GUI.Box, how would I implement a controller to fade in or out from the OnGUI lifecycle stage of the view?
View
using UnityEngine;
public class ExampleView : MonoBehaviour {
protected void OnGUI () {
GUI.Box(new Rect(0, 0, 100, 100), "Title");
}
}
If I instantiate a controller to change alpha of GUI.color it would need notification of Update() from the main view thread.
To roughly encapsulate functionality, if this were a single script it could be implemented as:
using UnityEngine;
public class ExampleView : MonoBehaviour {
private Color color;
protected void Start () {
color = Color.white;
}
protected void OnGUI () {
GUI.color = color;
GUI.Box(new Rect(0, 0, 100, 100), "Title");
}
protected void Update () {
if(color.a > 0)
color.a -= Time.deltaTime / 3;
}
}
Akin to how iTween animates changes to properties using iTween.fadeTo(gameObject, ... how can this be implemented for Unity3d GUI controls using statements like FadeOut()?
There's probably no way to target individual GUI controls unless multiple controller instances are specified OnGUI(). However, it would be cool to control isolated GUI instances such as fading in a GUI.Box followed by GUI.Label.
Are you looking for something like this?:
using UnityEngine;
public class ExampleView : MonoBehaviour {
private Color color;
private bool bFadeIn = false;
private bool bFadeOut = false;
protected void Start () {
color = Color.white;
}
public void FadeOut(){
bFadeOut = true;
bFadeIn = false;
}
public void FadeIn(){
bFadeIn = true;
bFadeOut = false;
}
protected void OnGUI () {
GUI.color = color;
GUI.Box(new Rect(0, 0, 100, 100), "Title");
}
protected void Update () {
if(bFadeOut && color.a > 0.0)color.a -= Time.deltaTime / 3;
if(bFadeIn && color.a < 1.0)color.a += Time.deltaTime / 3;
}
}
You might also want to include a flag to determine when the control is invisible and, if invisible, skip the full GuiRender function.
Dont know if this is what you are looking for, but its a simple way to add fade effect to gui..
using UnityEngine;
using System.Collections;
/**Fade In/Out Instructions:
* 1.Create bool fadeIn. Create float alpha.
* 2.Call Fade() method at start of OnGUI().
* 3.Put 'GUI.color = new Color(1,1,1,alpha)' above the elements you want to fade'.
* 4.To fade in, fadeIn = true.
* 5.To fade out, fadeIn = false.
* 6.To deactivate buttons on fade out, wrap gui in 'if(alpha > 0)'
**/
public class MainMenuGUI : MonoBehaviour {
int buttonWidth;
int buttonHeight;
public float alpha;
public bool fadeIn;
// Use this for initialization
void Start () {
buttonWidth = 100;
buttonHeight = 50;
fadeIn = true;
}
void OnGUI(){
Fade();
GUI.color = new Color(1,1,1,alpha);
if(alpha > 0)
{
if (GUI.Button (new Rect ((Screen.width/2)-50, (Screen.height/2)-(buttonHeight*4/2), 100, 50), "PLAY"))
{
fadeIn = false;
Debug.Log("Play pressed");
}
if (GUI.Button (new Rect ((Screen.width/2)-50, ((Screen.height/2)-(buttonHeight*4/2)+ buttonHeight), 100, 50), "SCORES"))
{
Debug.Log("Scores pressed");
}
if (GUI.Button (new Rect ((Screen.width/2)-50, ((Screen.height/2)-(buttonHeight*4/2)+ buttonHeight*2), 100, 50), "OPTIONS"))
{
Debug.Log("Options pressed");
}
if (GUI.Button (new Rect ((Screen.width/2)-50, ((Screen.height/2)-(buttonHeight*4/2)+ buttonHeight*3), 100, 50), "EXIT"))
{
Debug.Log("Exit pressed");
}
}
}
void Fade(){
if(fadeIn){
alpha = Mathf.Clamp(alpha+0.01f,0,1);
}else{
alpha = Mathf.Clamp(alpha-0.01f,0,1);
}
}
}
Good luck on your game :)