I've begun working on an early alpha menu for my game and I've was wondering how to exclude items in an array, specifically in unity. I'm trying to make every item except the currently used one. I don't know how I should go about it, if anyone could help, that would be amazing.
here's my current code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class CS
{
public List<GameObject> CanvasButtons;
}
public class CanvasSwitcher : MonoBehaviour
{
public List<CS> Screen = new List<CS>();
static int switcher;
public static void ScreenSwitchPlus()
{
switcher += 1;
}
public static void ScreenSwitchMinus()
{
switcher -= 1;
}
public void Update()
{
foreach(GameObject l in Screen[switcher].CanvasButtons)
{
l.SetActive(true);
}
}
}
It would be wiser to use for loop instead of foreach loop here:
public void Update()
{
int ignore = 2;
for(int i = 0; i < Screen[switcher].CanvasButtons.Count; i++)
{
if(i != ignore)
Screen[switcher].CanvasButtons[i].SetActive(true);
else
Screen[switcher].CanvasButtons[i].SetActive(false);
}
}
It could be even shorter without if (admit less readable):
public void Update()
{
int ignore = 2;
for(int i = 0; i < Screen[switcher].CanvasButtons.Count; i++)
{
Screen[switcher].CanvasButtons[i].SetActive(i != ignore);
}
}
... and even shorter with taking CanvasButtons out of loop:
public void Update()
{
int ignore = 2;
var collection = Screen[switcher].CanvasButtons;
for(int i = 0; i < collection.Count; i++)
{
collection[i].SetActive(i != ignore);
}
}
I got it! I was a bit null-brained for a while there, I messed up a few values in the second for statement, but I got it. I'll post the code here. I keep forgetting little things in the math. Like I always say, I don't solve problems, I make them.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class CS
{
public List<GameObject> CanvasButtons;
}
public class CanvasSwitcher : MonoBehaviour
{
public List<CS> Screen = new List<CS>();
static int switcher;
public static void ScreenSwitchPlus()
{
switcher += 1;
}
public static void ScreenSwitchMinus()
{
switcher -= 1;
}
public void FixedUpdate()
{
List<CS> csco = Screen;
for(int i1 = 0; i1 < csco.Count;)
{
List<GameObject> collection = csco[i1].CanvasButtons;
for (int i = 0; i < collection.Count; i++)
{
collection[i].SetActive(i1 == switcher);
switch(i == collection.Count - 1)
{
case true:
i1++;
break;
}
}
}
}
}
I think you are making things too complicated.
It could simply be
public void Update()
{
for(var i = 0; i < Screen.Count; i++)
{
foreach(var button in Screen[i].CanvasButtons)
{
button.SetActive(i == switcher);
}
}
}
Two more points though.
First I would make sure that switcher is actually a valid value. You either want to clamp the value to stay within the index range like
public static void ScreenSwitchPlus()
{
switcher = Mathf.Clamp(switcher + 1, 0, Screen.Count);
}
public static void ScreenSwitchMinus()
{
switcher = Mathf.Clamp(switcher - 1, 0, Screen.Count);
}
or you could implement wrap around at the ends according to your needs like
public static void ScreenSwitchPlus()
{
switcher = (switcher + 1) % Screen.Count;
}
public static void ScreenSwitchMinus()
{
switcher -= 1;
if(switcher < 0) switcher = Screen.Count - 1;
}
and then finally as mentioned I wouldn't do this poll fetching the value in Update every frame at all but rather event driven.
If you really need to (I would claim it is just lazyness ;) ) have that value and methods static you could attach to an event like
private static event Action<int> OnSwitcherChanged;
public static void ScreenSwitchPlus()
{
switcher = (switcher + 1) % Screen.Count;
OnSwitcherChanged?.Invoke(switcher);
}
public static void ScreenSwitchMinus()
{
switcher -= 1;
if(switcher < 0) switcher = Screen.Count - 1;
OnSwitcherChanged?.Invoke(switcher);
}
and then listen to that event like
private void OnEnable()
{
OnSwitcherChanged += HandleSwitchChanged;
}
private void OnDisable()
{
OnSwitcherChanged -= HandleSwitchChanged;
}
private void HandleSwitchChanged(int newIndex)
{
for(var i = 0; i < Screen.Count; i++)
{
foreach(var button in Screen[i].CanvasButtons)
{
button.SetActive(i == switcher);
}
}
}
Try this
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class CS {
public List<GameObject> CanvasButtons;
}
public class CanvasSwitcher : MonoBehaviour {
public List<CS> Screen = new List<CS>();
private static bool m_changed = false;
private static int m_lastSwitcher = 0;
private static int m_switcher = 0;
static int switcher {
get {
return m_switcher;
}
set {
if ( switcher != value ) {
m_lastSwitcher = m_switcher;
m_changed = true;
m_switcher = value;
}
}
}
public static void ScreenSwitchPlus() {
switcher += 1;
}
public static void ScreenSwitchMinus() {
switcher -= 1;
}
private void Update() {
if ( m_changed ) {
UpdateCS();
m_changed = false;
}
}
void UpdateCS() {
if ( m_lastSwitcher < Screen.Count ) {
var canvasBtns = Screen[ m_lastSwitcher ].CanvasButtons;
for ( int i = 0; i < canvasBtns.Count; i++ ) {
canvasBtns[ i ].SetActive( false );
}
}
if ( switcher < Screen.Count ) {
var canvasBtns = Screen[ switcher ].CanvasButtons;
for ( int i = 0; i < canvasBtns.Count; i++ ) {
canvasBtns[ i ].SetActive( true );
}
}
}
}
Related
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
using UnityEngine.SceneManagement;
using System;
using UnityStandardAssets.Characters.ThirdPerson;
public class OnGameLoading : MonoBehaviour
{
public CinemachineFreeLook standUpCamera;
public CinemachineFreeLook closeLookCamera;
public CinemachineFreeLook gamePlayCamera;
void Update()
{
// When starting a new game
if (sceneName == "Game" &&
MenuController.LoadSceneForSavedGame == false && newGameStart == false)
{
ThirdPersonUserControl.stop = true;
standUpCamera.m_XAxis.m_MaxSpeed = 0;
standUpCamera.m_YAxis.m_MaxSpeed = 0;
closeLookCamera.m_XAxis.m_MaxSpeed = 0;
closeLookCamera.m_YAxis.m_MaxSpeed = 0;
gamePlayCamera.m_XAxis.m_MaxSpeed = 0;
gamePlayCamera.m_YAxis.m_MaxSpeed = 0;
}
}
}
Is there something easier to access the properties? This way it's working, but isn't it too much code to write or is it fine this way?
I use the advice of 'derHugo, At Least Vision'
Use a dictionary and in this specific use case why not use a method?
public class OnGameLoading : MonoBehaviour
{
public CinemachineFreeLook standUpCamera;
public CinemachineFreeLook closeLookCamera;
public CinemachineFreeLook gamePlayCamera;
public Dictionary<CinemachineCameraType, CinemachineFreeLook> cinemachineFreeLookCameras = new Dictionary<CinemachineCameraType, CinemachineFreeLook>();
private void Awake()
{
cinemachineFreeLookCameras.Add(CinemachineCameraType.standUpCamera, standUpCamera);
cinemachineFreeLookCameras.Add(CinemachineCameraType.closeLookCamera, closeLookCamera);
cinemachineFreeLookCameras.Add(CinemachineCameraType.gamePlayCamera, gamePlayCamera);
}
void Update()
{
// When starting a new game
if (sceneName == "Game" && MenuController.LoadSceneForSavedGame == false && newGameStart == false)
{
ThirdPersonUserControl.stop = true;
standUpCamera.m_XAxis.m_MaxSpeed = 0;
standUpCamera.m_YAxis.m_MaxSpeed = 0;
closeLookCamera.m_XAxis.m_MaxSpeed = 0;
closeLookCamera.m_YAxis.m_MaxSpeed = 0;
gamePlayCamera.m_XAxis.m_MaxSpeed = 0;
gamePlayCamera.m_YAxis.m_MaxSpeed = 0;
// Dictionary foreach
foreach (var item in cinemachineFreeLookCameras.Values)
{
item.m_XAxis.m_MaxSpeed = 0;
item.m_YAxis.m_MaxSpeed = 0;
}
// Dictionary for loop
for (int i = 0; i < cinemachineFreeLookCameras.Count; i++)
{
cinemachineFreeLookCameras.ElementAt(i).Value.m_XAxis.m_MaxSpeed = 0;
cinemachineFreeLookCameras.ElementAt(i).Value.m_YAxis.m_MaxSpeed = 0;
}
// Method
SetFreeLookCameraAxisMaxSpeed(standUpCamera,0,0);
SetFreeLookCameraAxisMaxSpeed(closeLookCamera, 0,0);
SetFreeLookCameraAxisMaxSpeed(gamePlayCamera, 0,0);
}
}
public void SetFreeLookCameraAxisMaxSpeed(CinemachineFreeLook camera,float x,float y)
{
camera.m_XAxis.m_MaxSpeed = x;
camera.m_YAxis.m_MaxSpeed = y;
}
}
public enum CinemachineCameraType
{
standUpCamera,
closeLookCamera,
gamePlayCamera
}
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 years ago.
thanks for reading, I am working on a small memory card game in C# using Unity. When I run a certain scene I am receiving constant errors.
The errors are as follows:
"NullReferenceException: Object reference not set to an instance of an object
Card.SetUpArt () (at Assets/Scripts/Card.cs:31)
Pairs.SetUpDeck () (at Assets/Scripts/Pairs.cs:62)
Pairs.Update () (at Assets/Scripts/Pairs.cs:23)"
My code is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class Card : MonoBehaviour {
public static bool NO_TURN = false;
[SerializeField]
private int cardState; //state of card
[SerializeField]
private int cardNumber; //Card value (1-13)
[SerializeField]
private bool _setUp = false;
private Sprite cBack; //card back (Green square)
private Sprite cFace; //card face (1-10 JQKA)
private GameObject pairsManager;
void Begin()
{
cardState = 1; //cards face down
pairsManager = GameObject.FindGameObjectWithTag("PairsManager");
}
public void SetUpArt()
{
cBack = pairsManager.GetComponent<Pairs>().GetBack(); //<--error
cFace = pairsManager.GetComponent<Pairs>().GetFace(cardNumber);
turnCard();//turns the card
}
public void turnCard() //handles turning of card
{
if (cardState == 0)
{
cardState = 1;
}
else if(cardState == 1)
{
cardState = 0;
}
if (cardState == 0 && !NO_TURN)
{
GetComponent<Image>().sprite = cBack; // shows card back
}
else if (cardState == 1 && !NO_TURN)
{
GetComponent<Image>().sprite = cFace; // shows card front
}
}
//setters and getters
public int Number
{
get {return cardNumber;}
set { cardNumber = value;}
}
public int State
{
get { return cardState; }
set { cardState = value; }
}
public bool SetUp
{
get { return _setUp; }
set { _setUp = value; }
}
public void PairCheck()
{
StartCoroutine(pause ());
}
IEnumerator pause()
{
yield return new WaitForSeconds(1);
if (cardState == 0)
{
GetComponent<Image>().sprite = cBack;
}
else if (cardState == 1)
{
GetComponent<Image>().sprite = cFace;
}
}
}
And:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using UnityEngine;
public class Pairs : MonoBehaviour {
public Sprite[] cardFace; //array of card faces
public Sprite cardBack;
public GameObject[] deck; //array of deck
public Text pairsCount;
private bool deckSetUp = false;
private int pairsLeft = 13;
// Update is called once per frame
void Update () {
if (!deckSetUp)
{
SetUpDeck();
}
if (Input.GetMouseButtonUp(0)) //detects left click
{
CheckDeck();
}
}//Update
void SetUpDeck()
{
for(int i = 0; i <deck.Length; i++)//resets cards
{
deck[i].GetComponent<Card>().SetUp = false;
}
for (int ix = 0; ix < 2; ix++) //sets up cards twice,
{
for(int i = 1; i < 14; i++)//sets up card value (2-10 JQKA)
{
bool test = false;
int val = 0;
while (!test)
{
val = Random.Range(0, deck.Length);
test = !(deck[val].GetComponent<Card>().SetUp);
}//while
//sets up cards
deck[val].GetComponent<Card>().Number = i;
deck[val].GetComponent<Card>().SetUp = true;
}//nested for
}//for
foreach (GameObject crd in deck)
{
crd.GetComponent<Card>().SetUpArt();
}
if (!deckSetUp)
{
deckSetUp = true;
}
}//SetUpDeck
public Sprite GetBack()
{
return cardBack;
}//getBack
public Sprite GetFace(int i)
{
return cardFace[i - 1];
}//getFace
void CheckDeck()
{
List < int > crd = new List<int>();
for(int i = 0; i < deck.Length; i++)
{
if(deck[i].GetComponent<Card>().State == 1)
{
crd.Add(i);
}
}
if(crd.Count == 2)
{
CompareCards(crd);
}
}//CheckDeck
void CompareCards(List<int> crd)
{
Card.NO_TURN = true; //stops cards turning
int x = 0;
if(deck[crd[0]].GetComponent<Card>().Number ==
deck[crd[1]].GetComponent<Card>().Number)
{
x = 2;
pairsLeft--;
pairsCount.text = "PAIRS REMAINING: " + pairsLeft;
if(pairsLeft == 0) // goes to home screen when game has been won
{
SceneManager.LoadScene("Home");
}
}
for(int j = 0; j < crd.Count; j++)
{
deck[crd[j]].GetComponent<Card>().State = x;
deck[crd[j]].GetComponent<Card>().PairCheck();
}
}//CompareCards
}
Any help anyone can offer would be greatly appreciated. Thank you in advance.
Link to GitHub Repository
I don't have knowledge about C#, as I'm working with java. You should initialize your variables. For more information I found this link What is a NullReferenceException, and how do I fix it?
I'm working on a final project for school (art school not computer science) where I'd like to make a live visualizer from brainwaves using a NeuroSky Mindwave brain reader and Unity. Unfortunately the teacher has very limited knowledge of coding as well and has left me in a very bad position...
I've built a music visualizer following this tutorial:
https://www.youtube.com/watch?v=ELLANEFw5B8
And also found an example Unity project which can live read and display raw data from the brainwave reader:
https://github.com/tgraupmann/unity_neurosky
Where I'm stuck is in trying to change the input of my visualizer to be the raw brainwave data rather than music.
Is someone able to help me move forward with this project? I've already looked at NeuroSky's Unity integration page and emailed them with no success.
Any help will be greatly appreciated, thanks so much!
Audio Spectrum Visualizer Code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spectrum : MonoBehaviour {
// Use this for initialization
public GameObject prefab;
public int numberOfObjects = 20;
public float radius = 5f;
public GameObject[] cubes;
void Start()
{
for (int i = 0; i < numberOfObjects; i++)
{
float angle = i * Mathf.PI * 2 / numberOfObjects;
Vector3 pos = new Vector3(Mathf.Cos(angle), 0, Mathf.Sin(angle)) * radius;
Instantiate(prefab, pos, Quaternion.identity);
}
cubes = GameObject.FindGameObjectsWithTag ("cubes");
}
// Update is called once per frame
void Update () {
float[] spectrum = AudioListener.GetSpectrumData (1024, 0, FFTWindow.Hamming);
for(int i = 0; i < numberOfObjects; i++)
{
Vector3 previousScale = cubes[i].transform.localScale;
previousScale.y = Mathf.Lerp (previousScale.y, spectrum[i] * 40, Time.deltaTime * 30);
cubes[i].transform.localScale = previousScale;
}
}
}
ThinkGear Connector Controller Code
(as far as I know the file that causes the raw data to be displayed in Unity like the screenshot commented below)
using System;
using System.Threading;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using MindWave.LitJson;
using System.Net.Sockets;
using System.Text;
using System.IO;
namespace MindWave
{
public class TGCConnectionController : MonoBehaviour
{
private TcpClient client;
private Stream stream;
private byte[] buffer;
public delegate void UpdateIntValueDelegate(int value);
public delegate void UpdateFloatValueDelegate(float value);
public event UpdateIntValueDelegate UpdatePoorSignalEvent;
public event UpdateIntValueDelegate UpdateAttentionEvent;
public event UpdateIntValueDelegate UpdateMeditationEvent;
public event UpdateIntValueDelegate UpdateRawdataEvent;
public event UpdateIntValueDelegate UpdateBlinkEvent;
public event UpdateFloatValueDelegate UpdateDeltaEvent;
public event UpdateFloatValueDelegate UpdateThetaEvent;
public event UpdateFloatValueDelegate UpdateLowAlphaEvent;
public event UpdateFloatValueDelegate UpdateHighAlphaEvent;
public event UpdateFloatValueDelegate UpdateLowBetaEvent;
public event UpdateFloatValueDelegate UpdateHighBetaEvent;
public event UpdateFloatValueDelegate UpdateLowGammaEvent;
public event UpdateFloatValueDelegate UpdateHighGammaEvent;
private bool m_waitForExit = true;
private void Start()
{
ThreadStart ts = new ThreadStart(Connect);
Thread thread = new Thread(ts);
thread.Start();
}
public void Disconnect()
{
stream.Close();
}
public void Connect()
{
client = new TcpClient("127.0.0.1", 13854);
stream = client.GetStream();
buffer = new byte[1024];
byte[] myWriteBuffer = Encoding.ASCII.GetBytes(#"{""enableRawOutput"": true, ""format"": ""Json""}");
stream.Write(myWriteBuffer, 0, myWriteBuffer.Length);
while (m_waitForExit)
{
ParseData();
Thread.Sleep(100);
}
}
public class PowerData
{
public float delta = 0;
public float theta = 0;
public float lowAlpha = 0;
public float highAlpha = 0;
public float lowBeta = 0;
public float highBeta = 0;
public float lowGamma = 0;
public float highGamma = 0;
public PowerData()
{
}
}
public class SenseData
{
public int attention = 0;
public int meditation = 0;
public PowerData eegPower = null;
public SenseData()
{
}
}
public class PackatData
{
public string status = string.Empty;
public int poorSignalLevel = 0;
public int rawEeg = 0;
public int blinkStrength = 0;
public SenseData eSense = null;
public PackatData()
{
}
}
int GetObjectCount(String json)
{
int level = 0;
int count = 0;
for (int i = 0; i < json.Length; ++i)
{
if (json[i].Equals('{'))
{
if (level == 0)
{
++count;
}
++level;
}
if (json[i].Equals('}'))
{
--level;
}
}
return count;
}
private void ParseData()
{
if (stream.CanRead)
{
try
{
int bytesRead = stream.Read(buffer, 0, buffer.Length);
List<PackatData> packets = new List<PackatData>();
String packet = Encoding.ASCII.GetString(buffer, 0, bytesRead);
if (!string.IsNullOrEmpty(packet))
{
Debug.Log(packet);
if (packet.Contains("}"))
{
int count = GetObjectCount(packet);
if (count == 1)
{
PackatData data = JsonMapper.ToObject<PackatData>(packet);
packets.Add(data);
}
else if (count > 1)
{
PackatData[] data = JsonMapper.ToObject<PackatData[]>(packet);
for (int index = 0; index < data.Length; ++index)
{
packets.Add(data[index]);
}
}
}
}
foreach (PackatData data in packets)
{
if (null == data)
{
continue;
}
if (data.poorSignalLevel != 0)
{
Debug.Log("data.poorSignalLevel: " + data.poorSignalLevel);
if (null != UpdatePoorSignalEvent)
{
UpdatePoorSignalEvent.Invoke(data.poorSignalLevel);
}
if (null != data.eSense)
{
if (UpdateAttentionEvent != null)
{
UpdateAttentionEvent(data.eSense.attention);
}
if (UpdateMeditationEvent != null)
{
UpdateMeditationEvent(data.eSense.meditation);
}
if (null != data.eSense.eegPower)
{
if (UpdateDeltaEvent != null)
{
UpdateDeltaEvent(data.eSense.eegPower.delta);
}
if (UpdateThetaEvent != null)
{
UpdateThetaEvent(data.eSense.eegPower.theta);
}
if (UpdateLowAlphaEvent != null)
{
UpdateLowAlphaEvent(data.eSense.eegPower.lowAlpha);
}
if (UpdateHighAlphaEvent != null)
{
UpdateHighAlphaEvent(data.eSense.eegPower.highAlpha);
}
if (UpdateLowBetaEvent != null)
{
UpdateLowBetaEvent(data.eSense.eegPower.lowBeta);
}
if (UpdateHighBetaEvent != null)
{
UpdateHighBetaEvent(data.eSense.eegPower.highBeta);
}
if (UpdateLowGammaEvent != null)
{
UpdateLowGammaEvent(data.eSense.eegPower.lowGamma);
}
if (UpdateHighGammaEvent != null)
{
UpdateHighGammaEvent(data.eSense.eegPower.highGamma);
}
}
}
}
else if (data.rawEeg != 0)
{
if (null != UpdateRawdataEvent)
{
UpdateRawdataEvent(data.rawEeg);
}
}
else if (data.blinkStrength != 0)
{
if (null != UpdateRawdataEvent)
{
UpdateBlinkEvent(data.blinkStrength);
}
}
}
}
catch (IOException e)
{
Debug.Log("IOException " + e);
}
catch (System.Exception e)
{
Debug.Log("Exception " + e);
}
}
} // end ParseData
void OnDisable()
{
m_waitForExit = false;
Disconnect();
}
private void OnApplicationQuit()
{
m_waitForExit = false;
Disconnect();
}
}
}
I think you missed the signal processing natural of this problem. Brainwave (if it's Beta wave) has relatively low frequency range, which is about 15 Hz to 30 Hz. Music, on the other hand is audible tone, whose frequency range is between 20 Hz to 20,000 Hz.
I am not familiar with the implementation of this particular visualizer you mentioned here, but if it's implemented as what visualizer suppose to do, the brainwave should show only show some small activity (depends on the amplitude of the brainwave signal) in the lowest frequency range in the spectrum.
There is a potential hack to fix the problem. Usually a visualizer will use FFT to transform a time series signal to its frequency domain, during which it will determine the frequency range the operation is performed over. If you can locate the code in the visualizer and change the frequency range to, say 1 Hz to 100 Hz, you should see a proper frequency spectrum.
I have a dictionary with gameobjects as the keys, which is n amount and gameobjects as the values, which is amount of possible 4.
Dictionary<GameObject, ArrayList> polesAttachedToFloor = new Dictionary<GameObject, ArrayList>();
public void AddFloor(GameObject floor)
{
if(floor != null)
{
polesAttachedToFloor.Add(floor, new ArrayList { null,null,null,null });
}
}
public void AddPole(GameObject floor, GameObject pole)
{
for (int i = 0; i <= 4; i++)
{
}
}
How do I iterate through the "values?"... and is there a more 'appropriate' way of doing what Im aiming for?
ArrayList poles;
if (polesAttachedToFloor.ContainsKey(floor))
{
poles = dictionary[floor];
}
if(poles!=null)
{
for (int i = 0; i <= 4; i++)
{
poles.Add(pole);
}
}
Try that inside you AddPole function.
There is how you should encapsulate that...Dont have unity running so may be some typos.
public class FloorManager:MonoBehaviour
{
public gameObject floorPrefab;
private List<Floor> floors;
void Start()
{
floors = new List<Floor>();
}
public void AddFloor()
{
//instantiate prefab // gameObject floorGo = Instantiate....
Floor floorScript = floorGo.getComponent<Floor>();
floors.Add(floorScript);
floorScript.AddPoles();
}
public void RemoveFloor(Floor floor)
{
floors[floors.IndexOf(floor)].gameObject.Destory();
floors.Remove(floor);
}
}
public class Floor : MonoBehaviour
{
public gameObject polePrefab;
public Pole [] poles = new Pole[4];
public void AddPoles()
{
for (int i = 0; i < 4; i++)
{
//instantiate prefab // gameObject poleGo = Instantiate....
Pole poleScript = poleGo.getComponent<Pole>();
poles[i]=poleScript;
}
}
}
public class Pole : MonoBehaviour
{
//some logic here if needed...Destroy...Damage...
}
Play with Enumerator :D Have fun
public void AddPole(GameObject floor, GameObject pole)
{
var enumerator = polesAttachedToFloor.GetEnumerator ();
for (int i = 0; i <= 4; i++)
{
if (enumerator.MoveNext ()) {
var item = enumerator.Current;
}
}
}
Please help me, I'm newbie with c# language. I've try to make simply application quiz, but I get problem that I can't end the process after the last question of quiz.
The script that I have below:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Quiz : MonoBehaviour {
[System.Serializable]
public class Question{
public string NoSoal;
public string TextSoal;
public string Pilihan1;
public string Pilihan2;
public string Pilihan3;
public string Pilihan4;
public int qKeyAnswer;
public int qUserAnswer;
}
public int BanyakPilihan;
public GUISkin mySkin;
private float Score;
public Question[] pertanyaan;
private GameObject coba;
private Text nil;
private GameObject Canvas;
// Use this for initialization
void Start () {
BanyakPilihan = 0;
Score = 0;
Canvas=GameObject.Find("Canvas");
}
// Update is called once per frame
void Update () {
}
void OnGUI () {
GUI.skin = mySkin;
GUILayout.BeginArea(new Rect((Screen.width/2)-200, 100 ,400, 450));
GUILayout.Box(Score.ToString("F1"));
GUILayout.Label(pertanyaan[BanyakPilihan].TextSoal);
if (GUILayout.Button(pertanyaan[BanyakPilihan].Pilihan1,mySkin.button)){
pertanyaan[BanyakPilihan].qUserAnswer = 1;
CalculateResult();
GoNextQuestion();
}
if (GUILayout.Button(pertanyaan[BanyakPilihan].Pilihan2)){
pertanyaan[BanyakPilihan].qUserAnswer = 2;
CalculateResult();
GoNextQuestion();
}
if (GUILayout.Button(pertanyaan[BanyakPilihan].Pilihan3)){
pertanyaan[BanyakPilihan].qUserAnswer = 3;
CalculateResult();
GoNextQuestion();
}
if (GUILayout.Button(pertanyaan[BanyakPilihan].Pilihan4)){
pertanyaan[BanyakPilihan].qUserAnswer = 4;
CalculateResult();
GoNextQuestion();
}
GUILayout.EndArea();
}
void GoNextQuestion(){
if (BanyakPilihan < pertanyaan.Length-1){
BanyakPilihan++;
}
}
void CalculateResult(){
float Total = 0;
for (int i=0; i< pertanyaan.Length; i++){
if (pertanyaan[i].qKeyAnswer == pertanyaan[i].qUserAnswer){
Total = Total + 1;
}
}
Total = Total / pertanyaan.Length * 100;
Score = Total;
}
}
Please help me to solve this problem.
You could try this:
void GoNextQuestion(){
GUI.skin=mySkin;
GUILayout.BeginArea(new Rect((Screen.width/2)-200, 100 ,400, 450));
if (BanyakPilihan < pertanyaan.Length-1){
BanyakPilihan++;
} else {
MessageBox.Show("The end");
Application.Exit();
}
}