- Home /
Change variable value using new UI Button
Basically what I am trying to achieve is changing the variable value when I click a button. This is the code where I change the variable through a function
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class LocalPlayer : MonoBehaviour
{
//Define All Classes
public int playerClass;
public void RunnerClassValue() { playerClass = 1; }
public void KillerClassValue() { playerClass = 2; }
public void SpectatorClassValue() { playerClass = 3; }
void Update()
{
Debug.Log("PlayerClass: " + playerClass);
}
}
Image with the button to see that I set the correct function
Basically the problem is that in the update the Debug keeps display 0 instead of 1 or 2 or 3 after I click the button. If I add a debug in the function it displays the function value but not in update.
Works fine with me. Copy pasted your code and I get what should be. On the other hand, if you added two of that scripts, one of them will display 0.
Answer by kilijouli · Mar 11, 2016 at 02:57 PM
it's been more than a year i know, but i actually was facing the same problem until very recently. So i'm posting this to anyone who, like me, is having trouble with that. I Actually used the SendMessage() function to call another function in the script attached to the game object i was trying to access. So here's my suggestion.
You should add the following script to your button prefab:
**using** UnityEngine;
**using** System.Collections;
**using** UnityEngine.UI;
public class ButtonTest : MonoBehaviour {
Button button = null;
string tag;
void Start ()
{
button = gameObject.GetComponent<Button>();
button.onClick.AddListener(() =>{Click();});
tag = transform.tag;
}
void Click ()
{
switch (tag)
{
case "Runner":
GameObject.FindGameObjectWithTag("player").SendMessage ("RunnerClassValue");
break;
case "Killer":
GameObject.FindGameObjectWithTag("player").SendMessage ("KillerClassValue");
break;
case "Spectator":
GameObject.FindGameObjectWithTag("player").SendMessage ("SpectatorClassValue");
break;
}
}
}
so basically the line GameObject.FindGameObjectWithTag("player").SendMessage ("SpectatorClassValue"); will look for any game object with the tag "player", look in his components for the functions put as argument in the SendMessage and call them.
Answer by boowman · Dec 22, 2014 at 12:47 PM
Ok so I just found out why it doesn't work. Basically LocalPlayer script is attached to a PlayerPref which will get instantiated when I press Play. Any way to fix that?