How to make dialogue choices change properly? - c#

I've been trying to implement a dialogue system which will let select a choice in a dialogue. Unity shows no errors, dialogue choices are displayed correctly, and yet a weird thing happens - when I press down arrow key (which is supposed to change the selected choice) the othe choices isn't highlighted and is shown just for a second.
Here is the code for the choice box:
public class ChoiceBox : MonoBehaviour
{
[SerializeField] ChoiceText choiceTextPrefab;
bool choiceSelected = false;
List<ChoiceText> choiceTexts;
int currentChoice;
public IEnumerator ShowChoices(List<string> choices, Action<int> onChoiceSelected)
{
choiceSelected = false;
currentChoice = 0;
gameObject.SetActive(true);
foreach (Transform child in transform)
{
Destroy(child.gameObject);
}
choiceTexts = new List<ChoiceText>();
foreach (var choice in choices)
{
var choiceTextObj = Instantiate(choiceTextPrefab, transform);
choiceTextObj.TextField.text = choice;
choiceTexts.Add(choiceTextObj);
}
yield return new WaitUntil(() => choiceSelected == true);
onChoiceSelected?.Invoke(currentChoice);
Debug.Log("choice is selected"); //this is showing in the console, but the choice box doesn't disappear
gameObject.SetActive(false);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.DownArrow))
++currentChoice;
else if (Input.GetKeyDown(KeyCode.UpArrow))
--currentChoice;
currentChoice = Mathf.Clamp(currentChoice, 0, choiceTexts.Count - 1);
for (int i = 0; i < choiceTexts.Count; i++)
{
choiceTexts[i].SetSelected(i == currentChoice);
}
if (Input.GetKeyDown(KeyCode.Return))
choiceSelected = true;
}
Then for the dialogue manager:
public class DialogueManager : MonoBehaviour
{
public Text dialogueName;
public Text dialogueText;
public static DialogueManager instance;
public int activeLineIndex;
public Animator anim;
public float typingSpeed = 0.2f;
public bool canPressE = true;
public bool makeYourChoice = false;
List<string> choices = new List<string>();
List<int> Action = new List<int>();
public bool dialogueFinished = false;
[SerializeField] ChoiceBox choiceBox;
public void EnqueueDialogue(DialogueBase db)
{
canPressE = false;
dialogueInfo.Clear();
foreach(DialogueBase.Info info in db.dialogueInfo)
{
dialogueInfo.Enqueue(info);
}
anim.SetBool("isopen", true);
DequeueDialogue();
}
public void DequeueDialogue()
{
if (dialogueInfo.Count == 0)
{
dialogueFinished = true;
StartCoroutine(DisplayChoices(choices));
makeYourChoice = true;
return;
}
if (makeYourChoice)
{
EndDialogue();
return;
}
StopAllCoroutines();
DialogueBase.Info info = dialogueInfo.Dequeue();
dialogueName.text = info.myName;
dialogueText.text = info.dialogueText;
StartCoroutine(TypeText(info));
}
public IEnumerator DisplayChoices(List<string> choices = null, Action<int> onChoiceSelected = null)
{
if ((choices != null) && choices.Count > 1)
{
yield return choiceBox.ShowChoices(choices, onChoiceSelected);
}
else
{
yield return null;
}
}
IEnumerator TypeText(DialogueBase.Info info)
{
dialogueText.text = "";
foreach (char letter in info.dialogueText.ToCharArray())
{
yield return new WaitForSeconds(typingSpeed);
dialogueText.text += letter;
yield return null;
}
}
void EndDialogue()
{
anim.SetBool("isopen", false);
}
public void GetNextLine()
{
if (!canPressE)
{
DequeueDialogue();
Debug.Log("dalshe");
}
}
public void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
GetNextLine();
}
}
public Queue<DialogueBase.Info> dialogueInfo;
public void Start()
{
dialogueInfo = new Queue<DialogueBase.Info>();
canPressE = true;
}
public void Awake()
{
if (instance != null)
{
Debug.Log("fix this" + gameObject.name);
}
else
{
instance = this;
}
}
}
For the choice text:
public class ChoiceText : MonoBehaviour
{
Text myText;
TextMeshProUGUI choiceText;
private void Awake()
{
choiceText = GetComponent<TextMeshProUGUI>();
}
public void SetSelected(bool selected)
{
choiceText.color = (selected) ? GlobalSettings.i.HighlightedColor: Color.blue;
}
public TextMeshProUGUI TextField => choiceText;
}
And for the object which the player collides and has a dialogue with:
if (Input.GetKeyDown(KeyCode.E) )
{
onTriggerEnter.Invoke();
dialogueStarted = true;
Debug.Log("запускаем диалог");
}
if (dialogueStarted && dM.dialogueFinished)
StartCoroutine(ShowDialogueOptions());
public IEnumerator ShowDialogueOptions()
{
int selectedChoice = 1;
Debug.Log("show choices");
yield return DialogueManager.instance.DisplayChoices(new List<string> { "Yes", "No" }, (choiceIndex) => selectedChoice = choiceIndex);
if(selectedChoice == 0) //"Yes"
{
Debug.Log("Cool"); //this is shown in the console
}
else if (selectedChoice == 1) //"No"
{
Debug.Log("You suck"); //this is never shown in the console
}
Only one choice ("No") is highlighted with blue, but the other one isn't showing at all. However, when I press down arrow key, it is shown in white colour just for a moment so that it's barely visible. What is shown in the console is marked in comments. Thank you all in advance.

Related

text mesh pro text isnt going in text slot

So apparently, i was working on my games dialogue and of course, i have to put the text in the text slot for my code. I tried putting it in the slot but it didnt work. I tried changing the "Text" to "TextMesh" but still, didnt work.
this is my code that i tried for the game.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Goose : MonoBehaviour
{
public GameObject dialoguePanel;
public TextMesh dialogueText;
public string[] dialogue;
private int index;
public float wordSpeed;
public bool playerIsClose;
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.E) && playerIsClose)
{
if(dialoguePanel.activeInHierarchy)
{
zeroText();
}
else
{
dialoguePanel.SetActive(true);
StartCoroutine(Typing());
}
}
}
public void zeroText()
{
dialogueText.text = "";
index = 0;
dialoguePanel.SetActive(false);
}
IEnumerator Typing()
{
foreach(char letter in dialogue[index].ToCharArray())
{
dialogueText.text += letter;
yield return new WaitForSeconds(wordSpeed);
}
}
public void NextLine()
{
if(index < dialogue.Length - 1)
{
index++;
dialogueText.text = "";
StartCoroutine(Typing());
}
else
{
zeroText();
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if(other.CompareTag("Player"))
{
playerIsClose = true;
}
}
private void OnTriggerExit2D(Collider2D other)
{
if(other.CompareTag("Player"))
{
playerIsClose = false;
zeroText();
}
}
}
I think what you need is public TMP_Text dialogueText

How can I disable some objects in arrays?

I have a script for gun switching, it have an array to get the MeshRenderer component of all elements, then, i can enable the element that i want, but i cannot disable the others.
public class TrocarArma : MonoBehaviour
{
[Header("References")]
public int choosenGun = 0;
[Space(10)]
[SerializeField] MeshRenderer[] meshes = new MeshRenderer[4];
void Start()
{
SelectWeapon();
}
void Update()
{
ChangeGun();
}
void SelectWeapon()
{
int gunCount = 0;
meshes[0] = GameObject.Find("GravityGun").GetComponent<MeshRenderer>();
meshes[1] = GameObject.Find("IronBar").GetComponent<MeshRenderer>();
meshes[2] = GameObject.Find("Tablet").GetComponent<MeshRenderer>();
meshes[3] = null; //Will be filled later.
foreach(Transform gun in transform)
{
if (gunCount == choosenGun)
{
meshes[choosenGun].enabled = true;
}
else
{
///Code to make the others array meshes elements MeshRenderers disable.
}
gunCount++;
}
}
void ChangeGun()
{
int previousWeapon = choosenGun;
if (Input.GetAxis("Mouse ScrollWheel") < 0)
{
if(choosenGun >= transform.childCount -1)
{
choosenGun = 0;
}
else
{
choosenGun++;
}
}
if (Input.GetAxis("Mouse ScrollWheel") > 0)
{
if (choosenGun <= 0)
{
chooseGun = transform.childCount - 1;
}
else
{
chooseGun--;
}
}
if (previousWeapon != chooseGun)
{
SelectWeapon();
}
}
}
I simply not used SetActive(true)/(false) because I need my tablet active to upgrade my defenses. The video that i make this script: https://www.youtube.com/watch?v=Dn_BUIVdAPg , thanks for reading!
You have strange logic inside void SelectWeapon() method. But, I dare to suggest that the following code can help you:
foreach(Transform gun in transform)
{
if (gunCount == choosenGun)
{
meshes[choosenGun].enabled = true;
}
else
{
meshes[gunCount].enabled = false;
}
gunCount++;
}
or
foreach(Transform gun in transform)
{
switch(gunCount)
{
case 0:
meshes[choosenGun].enabled = true;
break;
default:
meshes[gunCount].enabled = false;
break;
}
gunCount++;
}
By the way:
meshes[3] = null; will throw an exception when you try to access the .enabled property. It is better not to allow such null elements, or always to check for null.

How to get random int values to a prefab which is called multiple times(without repeating same value)?

I have created a prefab which contains text (a*b=) and input field (to get user's answer). and I am calling this prefab 5 times using c# script. I have assigned a & b to random.range(1,10) so i can get 5 different sums. but in my case i am getting same values to all 5 sums.
I tried foreach loop and it is getting random numbers out of given range and on clicking check button it shows even correct answers in red(as incorrect).
This is the first time i am dealing with calling prefab multiple times via script. so need some help to solve it please.
TestModeQuestionUI.cs
using Helper.Keyboard;
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class TestModeQuestionUI : MonoBehaviour
{
internal RectTransform refRectTransform;
[SerializeField]
TextMeshProUGUI valueA; // valueB;
[SerializeField]
MyInputField AnswerInputField;
internal int id;
internal Action<TestModeQuestionUI> onSubmitValueOfInputFieldAction;
internal Action<TestModeQuestionUI> onSelectInputFieldAction;
Color defaultColorOfAnswer = new Color(0.19f, 0.19f, 0.19f, 1f);
Color correctColorOfAnswer = new Color(0f, 0.44f, 0f, 1f);
Color incorrectColorOfAnswer = new Color(1f, 0f, 0f, 1f);
public static TestModeQuestionUI curSelectedAnswerInputField;
//-------------------------------------------------------------------------
void Awake()
{
refRectTransform = GetComponent<RectTransform>();
}
private void SetNextAnswerInputFieldAsSelected(TestModeQuestionUI
curSelectedAnswerInputField)
{
throw new NotImplementedException();
}
public void SetQuestionLabel(string v)
{
valueA.text = v;
}
public void ActiveAnswerInputField(bool active)
{
AnswerInputField.gameObject.SetActive(active);
}
public int GetAnswerInputField()
{
int result = -1;
int.TryParse(AnswerInputField.textComponent.text, out result);
return result;
}
public void SetAnswerInputField(string msg)
{
AnswerInputField.textComponent.text = msg;
}
public void SelectAnswerInputField()
{
DeSelectCurSelectedAnswerInputField();
AnswerInputField.ActivateInputField();
curSelectedAnswerInputField = this;
}
public static void DeSelectCurSelectedAnswerInputField()
{
if (curSelectedAnswerInputField != null)
{
curSelectedAnswerInputField.AnswerInputField.DeactivateInputField();
}
curSelectedAnswerInputField = null;
}
public void SetResultOfAnswerInputField(int result)
{
switch (result)
{
//==================================
// Default Color For Answer Has Not Checked
case 0:
AnswerInputField.textComponent.color = defaultColorOfAnswer;
break;
//==================================
// Correct Color For Answer Has Checked Correct
case 1:
AnswerInputField.textComponent.color = correctColorOfAnswer;
break;
//==================================
// Incorrect Color For Answer Has Checked Incorrect
case 2:
AnswerInputField.textComponent.color = incorrectColorOfAnswer;
break;
}
}
public void OnSelectInputField()
{
//Debug.Log("On Select : " + id);
if (curSelectedAnswerInputField != this)
DeSelectCurSelectedAnswerInputField();
curSelectedAnswerInputField = this;
if (onSelectInputFieldAction != null)
onSelectInputFieldAction(this);
}
public void OnSubmitValueOfInputField()
{
if (onSubmitValueOfInputFieldAction != null)
onSubmitValueOfInputFieldAction(this);
}
}
TestModeManager.cs
public class TestModeManager : MonoBehaviour
{
public static TestModeManager instance;
[SerializeField]
GameObject refTestModeQuestionExampleParent;
[SerializeField]
GameObject refTestModeQuestionExamplePrefab;
[SerializeField]
GameObject checkButton;
[SerializeField]
GameObject nextButton;
private int a, b;
List<TestModeQuestionUI> testModeQuestionExampleList;
void Start()
{
CreateUI();
}
void Update()
{
#if UNITY_EDITOR
if (Input.GetKeyDown(KeyCode.KeypadEnter))
{ SetNextAnswerInputFieldAsSelected(TestModeQuestionUI.curSelectedAnswerInputField);
}
#endif
if (Input.GetKeyDown(KeyCode.Escape))
{
if (Keyboard.instance.gameObject.activeInHierarchy)
Keyboard.Close();
else
Application.Quit();
}
}
void CreateUI()
{
GameObject _GO;
TestModeQuestionUI _TestModeQuestionUIRefrence;
if (testModeQuestionExampleList == null)
testModeQuestionExampleList = new List<TestModeQuestionUI>();
// a = UnityEngine.Random.Range(1, 20);
// b = UnityEngine.Random.Range(1, 10);
for (int id = 1; id <= 5; id++)
{
_GO = Instantiate(refTestModeQuestionExamplePrefab,
refTestModeQuestionExampleParent.transform);
_GO.name = "TestModeQuestion Example " + id;
_TestModeQuestionUIRefrence = _GO.GetComponent<TestModeQuestionUI>
();
_TestModeQuestionUIRefrence.id = id;
_TestModeQuestionUIRefrence.onSubmitValueOfInputFieldAction =
SetNextAnswerInputFieldAsSelected;
testModeQuestionExampleList.Add(_TestModeQuestionUIRefrence);
}
ResetUI();
}
void ResetUI()
{
// Reset Multiplication Examples
a = UnityEngine.Random.Range(1, 10);
b = UnityEngine.Random.Range(1, 10);
foreach (TestModeQuestionUI _TestModeQuestionUIRefrence in
testModeQuestionExampleList)
{
_TestModeQuestionUIRefrence.SetQuestionLabel(a + " " + b + " = ");
//loop to get 5 different sums
var questions = GameObject.FindGameObjectsWithTag("question");
foreach (var question in questions)
{
// a++;
//b++;
}
}
//==================================
// Set First Answer Input Field As Selected
SetNextAnswerInputFieldAsSelected();
}
void SetNextAnswerInputFieldAsSelected(TestModeQuestionUI _
TestModeQuestionUIRefrence = null)
{
if (_TestModeQuestionUIRefrence == null)
{
//==================================
// Get First Input Field And Set As Selected
_TestModeQuestionUIRefrence = GettestModeQuestionExampleList(1);
if (_TestModeQuestionUIRefrence != null)
_TestModeQuestionUIRefrence.SelectAnswerInputField();
}
else
{
//==================================
// Get Next Input Field And Set As Selected
_TestModeQuestionUIRefrence =
GettestModeQuestionExampleList(_TestModeQuestionUIRefrence.id + 1);
if (_TestModeQuestionUIRefrence != null)
_TestModeQuestionUIRefrence.SelectAnswerInputField();
else
{
Keyboard.Close();
StartCoroutine(highlighCheckButton());
}
}
}
TestModeQuestionUI GettestModeQuestionExampleList(int id)
{
foreach (TestModeQuestionUI _TestModeQuestionUIRefrence in
testModeQuestionExampleList)
{
if (_TestModeQuestionUIRefrence.id == id)
{
return _TestModeQuestionUIRefrence;
}
}
return null;
}
IEnumerator EnableKeyboardAfterSometime(float time)
{
yield return new WaitForSeconds(time);
Keyboard.Open();
}
IEnumerator highlighCheckButton()
{
checkButton.transform.localScale = new Vector3(1f, 1f, 1f);
float animtionTime = 0.3f;
float scaleUpTo = 1.2f;
for (int i = 0; i < 4; i++)
{
yield return AnimationController.animate(scaleCheckButton,
animtionTime, 1f, scaleUpTo);
yield return AnimationController.animate(scaleCheckButton,
animtionTime, scaleUpTo, 1f);
}
checkButton.transform.localScale = new Vector3(1f, 1f, 1f);
}
void scaleCheckButton(float value)
{
checkButton.transform.localScale = new Vector3(value, value, value);
}
public void CheckButton()
{
int answer;
foreach (TestModeQuestionUI _TestModeQuestionUIRefrence in
testModeQuestionExampleList)
{
answer = _TestModeQuestionUIRefrence.GetAnswerInputField();
if ((a * b) == answer)
{
_TestModeQuestionUIRefrence.SetResultOfAnswerInputField(1);
}
else
{
_TestModeQuestionUIRefrence.SetResultOfAnswerInputField(2);
}
}
checkButton.SetActive(false);
nextButton.SetActive(true);
}
public void NextButton()
{
ResetUI();
nextButton.SetActive(false);
}
You should get the random value inside the loop, otherwise you get the same values.
foreach (TestModeQuestionUI _TestModeQuestionUIRefrence in testModeQuestionExampleList)
{
int a = UnityEngine.Random.Range(1, 10);
int b = UnityEngine.Random.Range(1, 10);
_TestModeQuestionUIRefrence.SetQuestionLabel(a, b);
}
You also should save a and b in TestModeQuestionUI because they are different betweent instances.
public class TestModeQuestionUI : MonoBehaviour
{
private int a, b;
public void SetQuestionLabel(int a, int b)
{
this.a = a;
this.b = b;
valueA.text = a + " " + b + " = ";
}
}
You have a lot of UI stuff but if i were you and if i do not want to get duplicates i would create a separate script for getting random values like this:
public class RandomIntegers {
private static List<int> myNumbersA = new List<int>();
private static List<int> myNumbersB = new List<int>();
public static void RandomValues(out int a,out int b)
{
if (myNumbersA.Count == 0)
{
for (int i = 0; i < 10; i++)
{
myNumbersA.Add(i + 1);
myNumbersB.Add(i + 1);
}
}
int indexA = Random.Range(0, myNumbersA.Count);
int indexB = Random.Range(0, myNumbersB.Count);
a = myNumbersA[indexA];
b = myNumbersB[indexB];
myNumbersA.RemoveAt(indexA);
myNumbersB.RemoveAt(indexB);
}
}
Then in your ResetUI function you can call this function using
RandomIntegers.RandomValues(out a,out b); The reason why i implemented it this way is instances of your prefab can access it when they are instantiated and since it is static you will not get same random results for a and b. But lets say you might get 6 for a and 8 for b but also 8 for a and 6 for b both will result as 48 at the end.

PUN 2 Not Connecting Players

I'm developing a game with Unity and I´'m using Photon's PUN 2 To manage the game's online mode, before, the online connect and list the rooms of the lobby very well, but, I don't know why it isn't working now. Now I can't joina room by seraching it with JoinRoom(RoomName) or JoinRandomRoom(), it just searches a room, then, marks the current state to "Joining" and goes back to the lobby. Also, need to tell that the rooms in lobby aren´t listing, even waiting 5 miutes or more in a room.
Here's my code, thanks:
private Button B;
private Text T;
private AudioSource Audio;
public AudioClip OK, Fail;
void Start ()
{
GameObject.Find("StartPanel").GetComponent<Animator>().SetBool("Show", true);
Audio = GetComponent<AudioSource>();
B = GetComponent<Button>();
T = GameObject.Find("ConnecText").GetComponent<Text>();
B.onClick.AddListener(Clicker);
}
void Clicker()
{
B.interactable = false;
Retrying();
T.text = "Connecting...";
PhotonNetwork.ConnectUsingSettings();
}
public override void OnDisconnected(DisconnectCause cause)
{
Failed();
}
public override void OnConnectedToMaster()
{
StartCoroutine(Connected());
}
IEnumerator Connected()
{
T.text = "Connected!";
Audio.clip = OK;
Audio.Play();
yield return new WaitForSeconds(1);
GameObject.Find("MenuPanel").SetActive(true);
GameObject.Find("MenuPanel").GetComponent<Animator>().SetBool("Show", true);
B.interactable = true;
}
void Retrying()
{
GameObject.Find("FailText").GetComponent<Text>().color = new Color(0, 0, 0, 0);
GameObject.Find("IFail").GetComponent<Image>().color = new Color(0, 0, 0, 0);
}
void Failed()
{
Color myRed = new Color();
ColorUtility.TryParseHtmlString("#DB9191FF", out myRed);
GameObject.Find("FailText").GetComponent<Text>().color = myRed;
GameObject.Find("IFail").GetComponent<Image>().color = Color.white;
T.text = "Retry";
Audio.clip = Fail;
Audio.Play();
B.interactable = true;
}
The list rooms code:
public GameObject roomPrefab;
public Sprite Four, Two, Three;
private string RoomName;
private int PlayerAmount;
private int MaxPlayers;
private Image I;
private Vector2 RoomVector;
private bool Lock = false;
public GameObject Content;
private List<RoomInfo> RoomList;
private bool IsntNull = false;
private Dictionary<string, RoomInfo> cachedRoomList;
private Dictionary<string, GameObject> roomListEntries;
private Dictionary<int, GameObject> playerListEntries;
private GameObject Handle;
public RooManager instance;
private void Awake()
{
if (instance != null)
{
DestroyImmediate(gameObject);
return;
}
DontDestroyOnLoad(gameObject);
instance = this;
cachedRoomList = new Dictionary<string, RoomInfo>();
roomListEntries = new Dictionary<string, GameObject>();
}
void Start()
{
//Content = GameObject.Find("Content").GetComponent<GameObject>();
RoomVector = new Vector2(450 /*370 */, this.transform.position.y);
}
private void ClearRoomListView()
{
foreach (GameObject entry in roomListEntries.Values)
{
Destroy(entry.gameObject);
}
roomListEntries.Clear();
}
public override void OnJoinedRoom()
{
if (playerListEntries == null)
{
playerListEntries = new Dictionary<int, GameObject>();
}
foreach (Player p in PhotonNetwork.PlayerList)
{
GameObject entry = Instantiate(roomPrefab);
playerListEntries.Add(p.ActorNumber, entry);
}
}
public override void OnLeftRoom()
{
foreach (GameObject entry in playerListEntries.Values)
{
Destroy(entry.gameObject);
}
playerListEntries.Clear();
playerListEntries = null;
}
public override void OnLeftLobby()
{
cachedRoomList.Clear();
ClearRoomListView();
}
private void Update()
{
print(PhotonNetwork.NetworkClientState);
}
private void UpdateRoomListView()
{
foreach (RoomInfo Item in cachedRoomList.Values)
{
RoomName = Item.Name;
PlayerAmount = Item.PlayerCount;
MaxPlayers = Item.MaxPlayers;
RoomVector.y -= 100;
GameObject RoomPrefab = Instantiate(roomPrefab, RoomVector, transform.rotation) as GameObject;
if (Item.PlayerCount == 0)
{
Destroy(RoomPrefab);
}
print(PhotonNetwork.CurrentLobby.Name);
RoomPrefab.transform.Find("RoomName").GetComponent<Text>().text = RoomName;
if (Item.Name.Length == 10)
{
Vector2 AddFive = new Vector2(RoomPrefab.transform.Find("RoomName").transform.position.x + 10, RoomPrefab.transform.Find("RoomName").transform.position.y);
RoomPrefab.transform.Find("RoomName").transform.position = AddFive;
}
if (Item.Name.Length >= 10)
{
Vector2 AddTen = new Vector2(RoomPrefab.transform.Find("RoomName").transform.position.x + 40, RoomPrefab.transform.Find("RoomName").transform.position.y + 20);
RoomPrefab.transform.Find("RoomName").transform.position = AddTen;
RoomPrefab.transform.Find("PlayerInt").GetComponent<Text>().fontSize = 47;
}
RoomPrefab.transform.Find("PlayerInt").GetComponent<Text>().text = PlayerAmount.ToString();
if (Item.MaxPlayers == 4)
{
RoomPrefab.transform.Find("IPlayerA").GetComponent<Image>().sprite = Four;
}
else if (Item.MaxPlayers == 2)
{
RoomPrefab.transform.Find("IPlayerA").GetComponent<Image>().sprite = Two;
}
else if (Item.MaxPlayers == 3)
{
RoomPrefab.transform.Find("IPlayerA").GetComponent<Image>().sprite = Three;
}
RoomPrefab.transform.SetParent(Content.transform);
}
}
public override void OnRoomListUpdate(List<RoomInfo> roomList)
{
ClearRoomListView();
UpdateCachedRoomList(roomList);
UpdateRoomListView();
print("Updated");
}
private void UpdateCachedRoomList(List<RoomInfo> roomList)
{
foreach (RoomInfo info in roomList)
{
// Remove room from cached room list if it got closed, became invisible or was marked as removed
if (!info.IsOpen || !info.IsVisible || info.RemovedFromList)
{
if (cachedRoomList.ContainsKey(info.Name))
{
cachedRoomList.Remove(info.Name);
}
continue;
}
// Update cached room info
if (cachedRoomList.ContainsKey(info.Name))
{
cachedRoomList[info.Name] = info;
}
// Add new room info to cache
else
{
cachedRoomList.Add(info.Name, info);
}
}
}
}
Need to say that in the list rooms code, the "Update" message yes prints, and theres no errors or warnings in the console.
OnPhotonCreateRoomFailed
OnPhotonJoinRoomFailed
you may want debug through override more callback
you can find all photon callbacks here

Unity Variable has not been assigned Error

I cannot figure out the issue, I deleted then remade the PlayTab object, but it no longer works... It is telling me it has not been assigned, but it has to my knowledge. Relatively new to Unity programming, any help would be great, the script below.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.Audio;
public class MainMenu : MonoBehaviour {
public GameObject Buttons;
public GameObject CreditsPanel;
public GameObject QuitPanel;
public GameObject Options;
public GameObject PlayTab;
public Slider audiosl;
public Slider graphicsl;
public Toggle fullscreen;
public string SceneName;
void Start (){
QualitySettings.SetQualityLevel (100);
//(int)PlayerPrefs.GetFloat("Quality")
AudioListener.volume = 100;
//PlayerPrefs.GetFloat("Volume");
int qualityLevel = QualitySettings.GetQualityLevel();
audiosl.value = AudioListener.volume;
graphicsl.value = qualityLevel;
}
void Update (){
Debug.Log ("Update");
AudioListener.volume = audiosl.value;
QualitySettings.SetQualityLevel ((int)graphicsl.value);
}
public void InGame(bool a){
if (a == true) {
Application.LoadLevel (SceneName);
} else {
//continue
}
}
public void Play(bool a){
Debug.Log ("Inside Play Function");
if (a == true) {
Debug.Log ("Inside If Statment");
PlayTab.SetActive(a);
Buttons.SetActive(!a);
Animation pl = PlayTab.GetComponent<Animation>();
pl.Play("EnterPlayMenu");
}else {
Debug.Log ("Else'd");
PlayTab.SetActive(a);
}
}
public void ShowMenu(bool a){
}
public void Option(bool a){
if (a == true) {
Options.SetActive(a);
Buttons.SetActive(!a);
Animation Opt = Options.GetComponent<Animation>();
Opt.Play("OptionEnter");
}if (a == false) {
Animation d = Buttons.GetComponent<Animation> ();
d.Play ("mainbuttonenter");
Options.SetActive (false);
}
}
public void Credits(bool a){
if (a == true) {
CreditsPanel.SetActive(a);
Buttons.SetActive(!a);
Animation cr = CreditsPanel.GetComponent<Animation>();
cr.Play("EnterCredits");
}else {
CreditsPanel.SetActive(a);
}
}
public void Quit(bool a){
if (a == true) {
QuitPanel.SetActive(a);
Buttons.SetActive(!a);
Animation q = QuitPanel.GetComponent<Animation>();
q.Play("EnterQuit");
}else {
QuitPanel.SetActive(a);
}
}
public void Exit(bool a){
if (a == false) {
Option(false);
Buttons.SetActive(true);
CreditsPanel.SetActive(false);
QuitPanel.SetActive(false);
Options.SetActive(false);
PlayTab.SetActive(false);
saveSettings();
}
if (a == true) {
Application.Quit();
}
}
public void saveSettings(){
PlayerPrefs.SetFloat ("Quality", QualitySettings.GetQualityLevel ());
PlayerPrefs.SetFloat ("Volume", AudioListener.volume);
}
public void FullScreen(bool a){
if (Screen.fullScreen == a) {
Screen.fullScreen = !a;
} else {
Screen.fullScreen = a;
}
}
}
As far as I see, you have only defined the playTab variable, but not assigned it.
EDIT:
Try displaying it at start, then automatically hiding it via code. Probably Unity don't initialize objects that are not visible on scene from the start.

Categories

Resources