Script broken after moving it to another gameobject - c#

I had a script that controlled my main menu that was on a GameObject and moved it to another gameobject and reconnected all the loose ends. now for some reason none of my buttons work, even with highlighting.
just had two gameobjects and moved the script between them using the editor
the script itself doesnt do much, just this:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class MainMenu : MonoBehaviour
{
public GameObject mainMenu;
public GameObject optionsMenu;
public GameObject modeMenu;
public Dropdown resolutionDropdown;
private Resolution[] resolutions;
public Toggle fullscreenToggle;
public void StartGameLocal()
{
SceneManager.LoadScene("Local2P");
}
public void StartGameAI()
{
SceneManager.LoadScene("AI2P");
}
public void MenuToOptions()
{
mainMenu.SetActive(false);
optionsMenu.SetActive(true);
}
public void OptionsToMenu()
{
mainMenu.SetActive(true);
optionsMenu.SetActive(false);
}
public void MenuToMode()
{
mainMenu.SetActive(false);
modeMenu.SetActive(true);
}
public void ModeToMenu()
{
mainMenu.SetActive(true);
modeMenu.SetActive(false);
}
public void ExitGame()
{
Application.Quit();
}
void Start()
{
resolutions = Screen.resolutions;
resolutionDropdown.ClearOptions();
List<string> options = new List<string>();
int currentResolutionIndex = 0;
for (int i = 0; i < resolutions.Length; i++)
{
string option = resolutions[i].width + " x " + resolutions[i].height;
options.Add(option);
if (resolutions[i].width == Screen.width && resolutions[i].height == Screen.height)
currentResolutionIndex = i;
}
resolutionDropdown.AddOptions(options);
resolutionDropdown.value = currentResolutionIndex;
resolutionDropdown.RefreshShownValue();
if (Screen.fullScreen == true)
{
fullscreenToggle.isOn = true;
}
}
public void SetResolution(int resolutionIndex)
{
Resolution resolution = resolutions[resolutionIndex];
Screen.SetResolution(resolution.width,
resolution.height, Screen.fullScreen);
PlayerPrefs.SetInt("ResolutionPreference", resolutionDropdown.value);
}
public void SetFullscreen(bool isFullscreen)
{
Screen.fullScreen = isFullscreen;
if (isFullscreen)
{
PlayerPrefs.SetInt("FullscreenPreference", 1);
}
else
{
PlayerPrefs.SetInt("FullscreenPreference", 0);
}
}
void Update()
{
if (Input.GetKey(KeyCode.Escape))
{
if (optionsMenu.activeSelf)
{
OptionsToMenu();
}
else if (optionsMenu.activeSelf)
{
ModeToMenu();
}
else
{
Application.Quit();
}
}
}
}
i dont know how to fix this and why my buttons just stopped working, even after reconnecting everything, but please help!
p.s. havent checked the update code to see if it worked, if yall have suggestions let me know

Your buttons likely pointed to the functions in this script in their OnClick handlers. If you moved the location of the script, you need to go to each of the buttons and hook those handlers back up.

Related

CreateRoom failed. Client is on MasterServer (must be Master Server for matchmaking)

I'm making a multiplayer game, when I create a room, there is an error, but I can still enter the room. Does the error affect the room? or do I just let it go? or is there something wrong with my coding? please help me fix it.
This is the error :
CreateRoom failed. Client is on MasterServer (must be Master Server
for matchmaking)but not ready for operations (State: Joining). Wait
for callback: OnJoinedLobby or OnConnectedToMaster.
UnityEngine.Debug:LogError (object)
Photon.Pun.PhotonNetwork:CreateRoom
(string,Photon.Realtime.RoomOptions,Photon.Realtime.TypedLobby,string[])
(at Assets/Photon/PhotonUnityNetworking/Code/PhotonNetwork.cs:1782)
Launcher:CreateRoom (int) (at Assets/Script/Launcher.cs:63)
Launcher:b__13_1 () (at Assets/Script/Launcher.cs:35)
UnityEngine.EventSystems.EventSystem:Update () (at
Library/PackageCache/com.unity.ugui#1.0.0/Runtime/EventSystem/EventSystem.cs:501)
This is the code :
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Pun;
using TMPro;
using Photon.Realtime;
using System.Linq;
public class Launcher : MonoBehaviourPunCallbacks
{
public static Launcher Instance;
[SerializeField] TMP_InputField roomNameInputField;
[SerializeField] TMP_Text errorText;
[SerializeField] TMP_Text roomNameText;
[SerializeField] Transform roomListContent;
[SerializeField] GameObject roomListItemPrefab;
[SerializeField] GameObject PlayerListItemPrefab;
[SerializeField] Transform playerListContent;
[SerializeField] GameObject startGameButton;
public GameObject twoPlayerButton;
public GameObject threePlayerButton;
public GameObject fourPlayerButton;
void Awake(){
Instance = this;
}
// Start is called before the first frame update
void Start()
{
Debug.Log("Connecting to Master");
PhotonNetwork.ConnectUsingSettings();
twoPlayerButton.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(() => CreateRoom(2));
threePlayerButton.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(() => CreateRoom(3));
fourPlayerButton.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(() => CreateRoom(4));
}
public override void OnConnectedToMaster()
{
Debug.Log("Connected to Master");
PhotonNetwork.JoinLobby();
PhotonNetwork.AutomaticallySyncScene = true;
}
public override void OnJoinedLobby()
{
MenuSetting.Instance.OpenMenu("firstmenu");
Debug.Log("Joined Lobby");
}
public void CreateRoom(int numPlayers){
if(string.IsNullOrEmpty(roomNameInputField.text)){
return;
}
RoomOptions roomOptions = new RoomOptions();
roomOptions.MaxPlayers = (byte)numPlayers;
ExitGames.Client.Photon.Hashtable customProperties = new ExitGames.Client.Photon.Hashtable();
customProperties.Add("MinPlayers", 2);
roomOptions.CustomRoomProperties = customProperties;
PhotonNetwork.CreateRoom(roomNameInputField.text + numPlayers, roomOptions);
MenuSetting.Instance.OpenMenu("Loading");
}
public override void OnJoinedRoom()
{
MenuSetting.Instance.OpenMenu("room");
roomNameText.text = PhotonNetwork.CurrentRoom.Name;
Player[] players = PhotonNetwork.PlayerList;
foreach(Transform child in playerListContent)
{
Destroy(child.gameObject);
}
for(int i = 0; i < players.Count(); i++){
Instantiate(PlayerListItemPrefab, playerListContent).GetComponent<PlayerListItem>().SetUp(players[i]);
}
if (players.Count() >= 2)
{
startGameButton.SetActive(PhotonNetwork.IsMasterClient); //only show the button if there are more than 2 players
}
else
{
startGameButton.SetActive(false); // hide the button if there are less than 2 players
}
}
public override void OnMasterClientSwitched(Player newMasterClient)
{
startGameButton.SetActive(PhotonNetwork.IsMasterClient);
}
public override void OnCreatedRoom()
{
Debug.Log("Room created successfully!");
}
public override void OnCreateRoomFailed(short returnCode, string message)
{
errorText.text = "Room Creation Failed: " + message;
MenuSetting.Instance.OpenMenu("error");
}
public void StartGame()
{
PhotonNetwork.LoadLevel(1);
}
public void LeaveRoom()
{
PhotonNetwork.LeaveRoom();
MenuSetting.Instance.OpenMenu("main_menu");
}
public void JoinRoom(RoomInfo info ){
PhotonNetwork.JoinRoom(info.Name);
MenuSetting.Instance.OpenMenu("loading");
}
public override void OnLeftRoom()
{
MenuSetting.Instance.OpenMenu("loading");
}
public override void OnRoomListUpdate(List<RoomInfo> roomList)
{
foreach(Transform trans in roomListContent){
Destroy(trans.gameObject);
}
for(int i = 0; i < roomList.Count; i++){
if(roomList[i].RemovedFromList)
continue;
Instantiate(roomListItemPrefab, roomListContent).GetComponent<RoomListItem>().SetUp(roomList[i]);
}
}
public override void OnPlayerEnteredRoom(Player newPlayer)
{
Instantiate(PlayerListItemPrefab, playerListContent).GetComponent<PlayerListItem>().SetUp(newPlayer);
}
}

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 to call array element that has bool value true unity C#

I have four buttons using the same prefab and holding 4 text elements from an array out of which only one is assigned bool value to true. I am trying to access that true element when any of false element is clicked. i want to highlight true element when the false element is clicked. can anyone please help me to achieve this functionality?
using simpleobjectpool
taking reference from unity quiz game tutorial
Thanks
Answer Button Script
public class AnswerButton : MonoBehaviour
{
public Text answerText;
private AnswerData answerData;
private GameController gameController;
private bool isCorrect;
void Start()
{
gameController = FindObjectOfType<GameController>();
}
public void Setup(AnswerData data)
{
answerData = data;
answerText.text = answerData.answerText;
}
public void HandleClick()
{
gameController.AnswerButtonClicked(answerData.isCorrect);
{
if (answerData.isCorrect)
{
}
if (!answerData.isCorrect)
{
}
}
Answer Data Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class AnswerData
{
public string answerText;
public bool isCorrect;
}
QuestionData Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class QuestionData
{
public string questionText;
public AnswerData[] answers;
}
Game Controller Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System;
public class GameController : MonoBehaviour
{
public Text questionText;
public Text scoreDisplayText;
public SimpleObjectPool answerButtonObjectPool;
public Transform answerButtonParent;
public GameObject questionPanel;
public GameObject roundOverPanel;
public GameObject levelsPanel;
private DataController dataController;
private RoundData currentRoundData;
private bool isRoundActive;
private float timeBeetweenQuestions = 3.0f;
private List<GameObject> answerButtonGameObjects = new List<GameObject>();
private QuestionData[] questionPool;
private int questionIndex;
private int qNumber = 0;
private List<int> questionIndexesChosen = new List<int>();
public int playerScore = 0;
public int totalQuestions;
private static int pointAddedForCorrectAnswer;
public AudioSource answerButtonClicked;
public AudioSource wrongAnswerClicked;
void Start ()
{
dataController = FindObjectOfType<DataController>();
currentRoundData = dataController.GetCurrentRoundData();
questionPool = currentRoundData.questions;
playerScore = 0;
questionIndex = 0;
scoreDisplayText.text = "Score: " + playerScore.ToString();
isRoundActive = true;
ShowQuestion();
}
private void ShowQuestion()
{
RemoveAnswerButtons();
QuestionData questionData = questionPool[questionIndex];
questionText.text = questionData.questionText;
for (int i = 0; i < questionData.answers.Length; i++)
{
GameObject answerButtonGameObject =
answerButtonObjectPool.GetObject();
answerButtonGameObjects.Add(answerButtonGameObject);
answerButtonGameObject.transform.SetParent(answerButtonParent);
AnswerButton answerButton =
answerButtonGameObject.GetComponent<AnswerButton>();
AnswerButton.Setup(questionData.answers[i]);
}
}
private void RemoveAnswerButtons()
{
while (answerButtonGameObjects.Count > 0)
{
answerButtonObjectPool.ReturnObject(answerButtonGameObjects[0]);
answerButtonGameObjects.RemoveAt(0);
}
}
IEnumerator TransitionToNextQuestion()
{
yield return new WaitForSeconds(timeBeetweenQuestions);
ShowQuestion();
}
IEnumerator WaitForFewSeconds()
{
yield return new WaitForSeconds(timeBeetweenQuestions);
EndRound();
}
IEnumerator ReturnCorrectButtonColor()
{
Debug.Log("im correct");
GetComponent<Button>().image.color = Color.green;
yield return new WaitForSeconds(seconds: 2.9f);
GetComponent<Button>().image.color = Color.white;
}
IEnumerator ReturnWrongButtonColor()
{
Debug.Log("im wrong");
GetComponent<Button>().image.color = Color.red;
yield return new WaitForSeconds(seconds: 2.9f);
GetComponent<Button>().image.color = Color.white;
}
public void AnswerButtonClicked (bool isCorrect)
{
if (isCorrect)
{
playerScore += currentRoundData.pointAddedForCorrectAnswer;
scoreDisplayText.text = "Score: " + playerScore.ToString();
//play coorect answer sound
answerButtonClicked.Play();
StartCoroutine(ReturnCorrectButtonColor());
}
if (!isCorrect)
{
//play wrong answer sound
answerButtonClicked = wrongAnswerClicked;
answerButtonClicked.Play();
StartCoroutine(ReturnWrongButtonColor());
// buttons = GameObject.FindGameObjectsWithTag("Answer");
// {
// foreach (GameObject button in buttons)
// {
// if (button.GetComponent<AnswerButton>
//().answerData.isCorrect)
// {
// button.GetComponent<AnswerButton>
// ().StartCoroutine(ReturnCorrectButtonColor());
// }
// }
//}
}
if (qNumber < questionPool.Length - 1) /
{
qNumber++;
StartCoroutine(TransitionToNextQuestion());
}
else
{
StartCoroutine(WaitForFewSeconds());
}
}
public void EndRound()
{
isRoundActive = false;
questionPanel.SetActive(false);
roundOverPanel.SetActive(true);
}
//on button click return to main menu
public void ReturnToMenu ()
{
SceneManager.LoadScene("MenuScreen");
}
}
In order to highlight both Wrong (the clicked one) and the Right buttons you need to have access to both buttons. This means that you can't do highlighting from HandleClick method of your Answer Button Script, as it only has access to itself, e.g. to the Wrong button.
The good thing is that this method notifies GameController that the button has been clicked. GameController knows about all the buttons, so it can easily highlight both buttons.
So, instead of launching your highlight subroutines from Answer Button's HandleClick, you should do this from GameController's AnswerButtonClicked: identify both the Right button and the clicked button there and launch appropriate subroutines for them.
Update:
For instance, your ReturnCorrectButtonColor would look like:
IEnumerator ReturnCorrectButtonColor( GameObject button )
{
Debug.Log("im correct");
button.GetComponent<Button>().image.color = Color.green;
yield return new WaitForSeconds(seconds: 2.9f);
button.GetComponent<Button>().image.color = Color.white;
}
so in AnswerButtonClicked you identify which button to highlight as a correct answer button and pass it as a paramter to this method:
StartCoroutine(ReturnCorrectButtonColor(correctButton));

Unity - Dialogue pops up

In Unity:
Could anybody tell me what I did wrong. I wanted to pop up a dialogue after you are nearby a charecter but somehow my code doesn't really work.
public class Interactable : MonoBehaviour {
[HideInInspector]
public NavMeshAgent playerAgent;
private bool hasInteracted;
public virtual void MoveToIneraction(NavMeshAgent playerAgent)
{
hasInteracted = false;
this.playerAgent = playerAgent;
playerAgent.stoppingDistance = 2.3f;
playerAgent.destination = this.transform.position;
Interact ();
}
void Update()
{
if (!!hasInteracted && playerAgent != null && playerAgent.pathPending)
{
if(playerAgent.remainingDistance <= playerAgent.stoppingDistance)
{
Interact();
hasInteracted = true;
}
}
}
public virtual void Interact()
{
Debug.Log("Interacted");
}
}
!!hasInteracted
It should be !hasInteracted, I guess

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