Hello i know this question might be a bad one but i have tried everything to my ability to acomplish this but i cant, so i have been making a rythm game and for the life of me i have made everything else other than the fail mechanism i just cant get it to work. i need to read the variable (MissedNotes) and make the code pause the time and show text saying (Too Many Notes Missed). I have made the place to insert the text in but i cant figure out how to do it at all. Im a begginer so any help is good, Thanks for helping me.
This is the code
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public AudioSource theMusic;
public AudioSource beatSfx;
public bool startPlaying;
public BeatScroller theBS;
public static GameManager instance;
public int currentScore;
public int scorePerNote = 2000;
public int scorePerGoodNote = 2500;
public int scorePerPerfectNote = 3000;
public int currentMultiplier;
public int multiplierTracker;
public int[] multiplierThresholds;
public Text scoreText;
public Text multiText;
public float totalNotes;
public float NormalHits;
public float GoodHits;
public float PerfectHits;
public float MissedHits;
public GameObject resultsScreen;
public Text percentHitText, normalsText, goodsText, perfectsText, missesText, rankText, finalScoreText;
public GameObject FAILTEXT;
// Start is called before the first frame update
void Start()
{
instance = this;
scoreText.text = "Press Any Key to Continue";
currentMultiplier = 1;
totalNotes = ((FindObjectsOfType<NoteObject>().Length) - 168);
}
// Update is called once per frame
void Update()
{
if (!startPlaying)
{
if (Input.anyKeyDown)
{
scoreText.text = "0";
startPlaying = true;
theBS.hasStarted = true;
theMusic.Play();
}
}
else
{
if (!theMusic.isPlaying && !resultsScreen.activeInHierarchy)
{
resultsScreen.SetActive(true);
normalsText.text = "" + NormalHits;
goodsText.text = "" + GoodHits;
perfectsText.text = "" + PerfectHits;
missesText.text = "" + MissedHits;
float totalHits = NormalHits + GoodHits + PerfectHits;
float percentHit = (totalHits / totalNotes) * 100f;
float totalMiss = MissedHits;
percentHitText.text = percentHit.ToString("F1") + "%";
string rankVal = "F";
if (percentHit >= 30)
{
rankVal = "D";
if (currentScore >= 550000)
{
rankVal = "C";
if (currentScore >= 750000)
{
rankVal = "B";
if (currentScore >= 900000)
{
rankVal = "A";
if (currentScore >= 950000)
{
rankVal = "S";
}
}
}
}
}
rankText.text = rankVal;
finalScoreText.text = currentScore.ToString();
}
}
}
public void NoteHit()
{
beatSfx.Play();
multiplierTracker++;
if ((currentMultiplier - 1) < multiplierThresholds.Length)
{
multiplierTracker++;
if (multiplierThresholds[currentMultiplier - 1] <= multiplierTracker)
{
multiplierTracker = 0;
currentMultiplier++;
}
}
scoreText.text = "" + currentScore;
multiText.text = "Score x" + currentMultiplier;
}
public void NormalHit()
{
UnityEngine.Debug.Log("Normal Hit");
currentScore += scorePerNote * currentMultiplier;
NormalHits++;
NoteHit();
}
public void GoodHit()
{
UnityEngine.Debug.Log("Good Hit");
currentScore += scorePerGoodNote * currentMultiplier;
GoodHits++;
NoteHit();
}
public void PerfectHit()
{
UnityEngine.Debug.Log("Perfect Hit");
currentScore += scorePerPerfectNote * currentMultiplier;
PerfectHits++;
NoteHit();
}
public void NoteMissed()
{
UnityEngine.Debug.Log("missed");
MissedHits++;
currentMultiplier = 1;
multiplierTracker = 0;
multiText.text = "Score x" + currentMultiplier;
}
}
There's nothing controlling time here so there's not really anything to do in this class to pause time. I'm also not seeing how the note hit functions are called.
It seems like there's some other class controlling the timing and note hit logic, and that's where you need to implement the logic to stop the game.
Once you've done that you can modify your NoteMissed method to trigger the game logic to stop when too many notes are missed.
Related
I have this gun that's supposed to have a cooldown after every shot by using time between shots += Time.deltaTime. The problem is that it's like timeBeetweenShots dosen't increase. Here's the part of my code that I think matters:
private void Update()
{
timeSinceLastShot += Time.deltaTime;
}
public bool CanShoot() => !gunData.reloading && timeSinceLastShot > 1 / (gunData.fireRate / 60);
public void Shoot()
{
if (gunData.currentAmmo > 0)
{
if (CanShoot())
{
Debug.Log("shooting");
gunData.currentAmmo--;
timeSinceLastShot = 0;
OnGunShot();
}
} else
{
StartCoroutine(Reload());
}
}
what did I do wrong?
I think we might need to use Time.time.
The doc link is just perfect for gun fire interval.
However I had edit your code.
using System.Collections;
using UnityEngine;
public class Gun : MonoBehaviour
{
GunData gunData; // gundata might be access from player
float timeSinceLastShot = 0;
private void Update()
{
}
public bool CanShoot() => !gunData.reloading && (timeSinceLastShot + gunData.fireRate) < Time.time;
public void Shoot()
{
if (gunData.currentAmmo > 0)
{
if (CanShoot())
{
Debug.Log("shooting");
gunData.currentAmmo--;
timeSinceLastShot = Time.time;// save the last time that shot
OnGunShot();
}
}
else
{
StartCoroutine(Reload());
}
}
public void OnGunShot()
{ // animation might be here
}
IEnumerator Reload()
{ // relaoding might be here
yield return new WaitForEndOfFrame();
}
}
public class GunData // just dummy data
{
public int currentAmmo = 10;
public float fireRate = 0.2f;
public bool reloading = false;
}
I inherited by my ex collegue a Unity game. Now I need to implement this behaviour. The game consist in a car drive by user using Logitech steering.
Now I need to show a Text every X minute in a part of the screen like "What level of anxiety do you have ? " Ad the user should to set a value from 0 to 9 using the Logitech steering but I really don't know where to start.
This is my manager class:
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
namespace DrivingTest
{
// Braking test Manager
public class BtManager : BaseTestManger
{
// Public variables
public BreakCar breakCar;
public float minBrakeThreshold = 0.2f;
internal int vehicalSpeed;
internal int noOfEvents;
internal float durationOfTest;
// Private variables
private IRDSPlayerControls playerControlCar;
protected int xSpeed;
protected int ySpeed;
private float brakeEventStartTime;
private float brakeEventDifferenceTime;
private SafetyDistanceCheck safetyDistanceCheck;
protected float totalSafetyDistance;
protected int totalSafetyDistanceCount;
private List<float> averageEventReactionTime = new List<float>();
#region Init
// Use this for initialization
public override void Start()
{
base.Start();
playerControlCar = car.GetComponent<IRDSPlayerControls>();
safetyDistanceCheck = car.GetComponent<SafetyDistanceCheck>();
}
public override void OnEnable()
{
base.OnEnable();
BreakCar.BrakeStart += BrakeCarEvent;
BreakCar.BrakeEventEnd += CallTestOver;
}
public override void OnDisable()
{
base.OnDisable();
BreakCar.BrakeStart -= BrakeCarEvent;
BreakCar.BrakeEventEnd -= CallTestOver;
}
protected override void SetUpCar()
{
car.AddComponent<SelfDriving>();
}
#endregion
/// <summary>
/// Calls the main Test over method.
/// </summary>
private void CallTestOver()
{
GameManager.Instance.Testover();
}
protected override void OnSceneLoaded(eTESTS test)
{
UiManager.Instance.UpdateInstructions(Constants.BT_INSTRUCTION);
}
protected override void GetApiParams()
{
NextTestOutput nextTestOutput = GameManager.Instance.currentTest;
if (nextTestOutput.content != null && nextTestOutput.content.Count > 0)
{
foreach (var item in nextTestOutput.content[0].listInputParameter)
{
switch ((ePARAMETERS)item.id)
{
case ePARAMETERS.X_SPEED:
xSpeed = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.Y_SPEED:
ySpeed = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.SPEED_OF_VEHICLE:
vehicalSpeed = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.NUMBER_OF_EVENTS:
noOfEvents = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.DURATION_OF_TEST:
durationOfTest = float.Parse(item.Value) * 60; //converting minutes into seconds
break;
}
}
SetupBrakeCar();
}
}
protected virtual void SetupBrakeCar()
{
DOTween.Clear();
durationOfTest = noOfEvents * Random.Range(10,20); // The random value is the time between two consecutive tests.
breakCar.SetInitalParams(new BrakeCarInit
{
carMaxSpeed = vehicalSpeed * 0.95f,
durationOfTest = durationOfTest,
noOfEvents = noOfEvents,
xSpeed = xSpeed,
ySpeed = ySpeed
});
breakCar.distanceCheck = true;
}
protected override void SubmitRestultToServer()
{
SubmitTest submitTest = new SubmitTest
{
outputParameters = new List<SaveOutputParameter>
{
new SaveOutputParameter
{
id = (int)ePARAMETERS.OUT_REACTION_TIME,
value = ((int)(GetEventReactionTimeAvg () * Constants.FLOAT_TO_INT_MULTIPLAYER)).ToString()
},
new SaveOutputParameter
{
id = (int)ePARAMETERS.OUT_AVG_RT,
value = GetReactionResult().ToString()
}
}
};
WebService.Instance.SendRequest(Constants.API_URL_FIRST_SAVE_TEST_RESULT, JsonUtility.ToJson(submitTest), SubmitedResultCallback);
}
protected override void ShowResult()
{
UiManager.Instance.UpdateStats(
(
"1. " + Constants.EVENT_REACTION + (GetEventReactionTimeAvg() * Constants.FLOAT_TO_INT_MULTIPLAYER).ToString("0.00") + "\n" +
"2. " + Constants.REACTION_TIME + reactionTest.GetReactionTimeAvg().ToString("0.00")
));
}
public void LateUpdate()
{
//Debug.Log("TH " + .Car.ThrottleInput1 + " TH " + playerControlCar.Car.ThrottleInput + " brake " + playerControlCar.Car.Brake + " brake IP " + playerControlCar.Car.BrakeInput);
//Debug.Log("BrakeCarEvent "+ brakeEventStartTime + " Player car " + playerControlCar.ThrottleInput1 + " minBrakeThreshold " + minBrakeThreshold);
if (brakeEventStartTime > 0 && playerControlCar.Car.ThrottleInput1 > minBrakeThreshold)
{
brakeEventDifferenceTime = Time.time - brakeEventStartTime;
Debug.Log("Brake event diff " + brakeEventDifferenceTime);
Debug.Log("Throttle " + playerControlCar.Car.ThrottleInput1);
averageEventReactionTime.Add(brakeEventDifferenceTime);
brakeEventStartTime = 0;
safetyDistanceCheck.GetSafetyDistance(SafetyDistance);
}
}
private void SafetyDistance(float obj)
{
totalSafetyDistance += obj;
++totalSafetyDistanceCount;
}
/// <summary>
/// Records the time when the car ahead starts braking
/// </summary>
protected void BrakeCarEvent()
{
brakeEventStartTime = Time.time;
Debug.Log("BrakeCarEvent ");
}
/// <summary>
/// calculates the average time taken to react
/// </summary>
public float GetEventReactionTimeAvg()
{
float avg = 0;
foreach (var item in averageEventReactionTime)
{
avg += item;
}//noofevents
return avg / (float)averageEventReactionTime.Count;
}
}
}
EDIT
I create new class FearTest:
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace DrivingTest
{
public class FearTest : MonoBehaviour
{
//public GameObject redDot;
public TextMeshPro textAnsia2;
public TextMesh textAnsia3;
public int shouldEvaluateTest = 0; // 0 - false, 1 - true
public int secondsInterval;
public int secondsToDisaply;
public int radiusR1;
public int radiusR2;
public int reactionTestDuration;
public int maxDots;
public float dotRadius = 1;
private float endTime;
private float dotDisaplyAtTime;
private List<float> dotDisplayReactTime = new List<float>();
private int missedSignals;
private int currentDotsCount;
private bool isReactionAlreadyGiven;
public bool ShouldEvaluateTest
{
get
{
return shouldEvaluateTest != 0;
}
}
void OnEnable()
{
GameManager.TestSceneLoaded += OnSceneLoaded;
}
private void OnDisable()
{
GameManager.TestSceneLoaded -= OnSceneLoaded;
}
#region Scene Loaded
private void OnSceneLoaded(eTESTS test)
{
if (SceneManager.GetActiveScene().name != test.ToString())
return;
Reset();
GetApiParams();
}
#endregion
private void GetApiParams()
{
#if UNITY_EDITOR
if (!GameManager.Instance)
{
Init();
return;
}
#endif
Debug.Log("called rt");
NextTestOutput nextTestOutput = GameManager.Instance.currentTest;
if (nextTestOutput.content != null && nextTestOutput.content.Count > 0)
{
foreach (var item in nextTestOutput.content[0].listInputParameter)
{
switch ((ePARAMETERS)item.id)
{
case ePARAMETERS.RT_ENABLE:
shouldEvaluateTest = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.RT_DURATION:
reactionTestDuration = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.RED_DOT_FREQ:
secondsInterval = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.RED_DOT_MAX_COUNT:
maxDots = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.RED_DOT_RADIUS_R1:
radiusR1 = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.RED_DOT_RADIUS_R2:
radiusR2 = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.RED_DOT_SIZE:
dotRadius = float.Parse(item.Value)/10f;
break;
case ePARAMETERS.RED_DOT_TIME:
secondsToDisaply = System.Convert.ToInt32(item.Value);
break;
}
}
Debug.Log("called rt "+ shouldEvaluateTest);
/*if (ShouldEvaluateTest)
{
Init();
}*/
Init();//dopo bisogna sistemare il shoudl evaluatetest
}
}
Coroutine displayCoroutine;
public void Init()
{
endTime = Time.time + reactionTestDuration + 10;
SetRedDotSize();
displayCoroutine = StartCoroutine(RedDotDisplay());
}
private IEnumerator RedDotDisplay()
{
yield return new WaitForSeconds(2);
while (true)
{
SetRandomDotPosition();
RedDot(true);
isReactionAlreadyGiven = false;
dotDisaplyAtTime = Time.time;
currentDotsCount++;
yield return new WaitForSeconds(secondsToDisaply);
if(!isReactionAlreadyGiven)
{
missedSignals++;
}
RedDot(false);
if ((reactionTestDuration > 0 && endTime <= Time.time) || (maxDots > 0 && currentDotsCount >= maxDots))
break;
float waitTime = secondsInterval - secondsToDisaply;
yield return new WaitForSeconds(waitTime);
}
}
private void Update()
{
if (!ShouldEvaluateTest)
return;
if (!isReactionAlreadyGiven && /*redDot.activeSelf &&*/ (LogitechGSDK.LogiIsConnected(0) && LogitechGSDK.LogiButtonIsPressed(0, 23)))
{
isReactionAlreadyGiven = true;
float reactionTime = Time.time - dotDisaplyAtTime;
Debug.Log("Reaction Time RT : " + reactionTime);
RedDot(false);
dotDisplayReactTime.Add(reactionTime);
}
}
public double GetReactionTimeAvg()
{
double avg = 0;
foreach (var item in dotDisplayReactTime)
{
avg += item;
}
//avg / currentDotsCount
return avg / (float)dotDisplayReactTime.Count;
}
public double GetMissedSignals()
{
return ((float) missedSignals / (float) currentDotsCount) * 100;
}
private void RedDot(bool state)
{
//redDot.SetActive(state);
textAnsia2.SetText("Pippo 2");
}
private void SetRedDotSize()
{
//redDot.transform.localScale *= dotRadius;
textAnsia2.transform.localScale *= dotRadius;
textAnsia3.transform.localScale *= dotRadius;
}
private void SetRandomDotPosition()
{
//redDot.GetComponent<RectTransform>().anchoredPosition = GetRandomPointBetweenTwoCircles(radiusR1, radiusR2)*scale;
float scale = ((Screen.height*0.9f) / radiusR2) * 0.9f;
Vector3 pos = GetRandomPointBetweenTwoCircles(radiusR1, radiusR2) * scale;
Debug.Log("RT temp pos : " + pos);
pos = new Vector3(500, 500, 0);
Debug.Log("RT pos : " + pos);
// redDot.transform.position = pos;
Vector3 pos2 = new Vector3(20, 20, 0);
Debug.Log("text ansia 2 : " + pos2);
textAnsia2.transform.position = pos2;
textAnsia3.transform.position = pos;
}
#region Getting Red Dot b/w 2 cricles
/*
Code from : https://gist.github.com/Ashwinning/89fa09b3aa3de4fd72c946a874b77658
*/
/// <summary>
/// Returns a random point in the space between two concentric circles.
/// </summary>
/// <param name="minRadius"></param>
/// <param name="maxRadius"></param>
/// <returns></returns>
Vector3 GetRandomPointBetweenTwoCircles(float minRadius, float maxRadius)
{
//Get a point on a unit circle (radius = 1) by normalizing a random point inside unit circle.
Vector3 randomUnitPoint = Random.insideUnitCircle.normalized;
//Now get a random point between the corresponding points on both the circles
return GetRandomVector3Between(randomUnitPoint * minRadius, randomUnitPoint * maxRadius);
}
/// <summary>
/// Returns a random vector3 between min and max. (Inclusive)
/// </summary>
/// <returns>The <see cref="UnityEngine.Vector3"/>.</returns>
/// <param name="min">Minimum.</param>
/// <param name="max">Max.</param>
Vector3 GetRandomVector3Between(Vector3 min, Vector3 max)
{
return min + Random.Range(0, 1) * (max - min);
}
#endregion
#region Reset
private void Reset()
{
if (displayCoroutine != null)
StopCoroutine(displayCoroutine);
RedDot(false);
shouldEvaluateTest = 0;
reactionTestDuration = 0;
secondsInterval = 0;
missedSignals = 0;
maxDots = 0;
radiusR1 = 0;
radiusR2 = 0;
dotRadius = 1;
secondsToDisaply = 0;
endTime = 0;
dotDisaplyAtTime = 0;
dotDisplayReactTime.Clear();
//redDot.transform.localScale = Vector3.one;
textAnsia2.transform.localScale = Vector3.one;
textAnsia3.transform.localScale = Vector3.one;
currentDotsCount = 0;
isReactionAlreadyGiven = true;
}
#endregion
}
}
When "SetRandomDotPosition" method is called, in my scene I can display in a random position of the screen the RedDot (that is a simple image with a red dot), but I m not able to display my textAnsia2. How can I fixed it ?
I hope this will help you to get started :
https://vimeo.com/709527359
the scripts:
https://imgur.com/a/csNKwEh
I hope that in the video i covered every step that i've made.
Edit: The only thing is for you to do is to make the input of the Wheel to work on the slider. Try to make a simple script: when the text is enabled then the input from a joystick to work on that . When is disabled switch it back for his purpose .
I'm busy with creating a school project where I need to integrate wave spawners.
For now, I used this video as an example and implemented it in my project.https://www.youtube.com/watch?v=q0SBfDFn2Bs
Everything is spawning fine and I also get my debug logs. The main problem is: I can't see my enemies. (not John Cena guys hahah, in that case it would be logic ;) )
I'm new to Unity and I like the interface and workflow but I have a lot to learn. I hope someone can help me out! :)
Source WaveSpawner.cs:
using UnityEngine;
using System.Collections;
public class WaveSpawner : MonoBehaviour
{
public enum SpawnState { SPAWNING, WAITING, COUNTING };
[System.Serializable]
public class Wave
{
public string name;
public Transform enemy;
public int count;
public float rate;
}
public Wave[] waves;
private int nextWave = 0;
public int NextWave
{
get { return nextWave + 1; }
}
public Transform[] spawnPoints;
public float timeBetweenWaves = 5f;
private float waveCountdown;
public float WaveCountdown
{
get { return waveCountdown; }
}
private float searchCountdown = 1f;
private SpawnState state = SpawnState.COUNTING;
public SpawnState State
{
get { return state; }
}
void Start()
{
if (spawnPoints.Length == 0)
{
Debug.LogError("No spawn points referenced.");
}
waveCountdown = timeBetweenWaves;
}
void Update()
{
if (state == SpawnState.WAITING)
{
if (!EnemyIsAlive())
{
WaveCompleted();
}
else
{
return;
}
}
if (waveCountdown <= 0)
{
if (state != SpawnState.SPAWNING)
{
StartCoroutine( SpawnWave ( waves[nextWave] ) );
}
}
else
{
waveCountdown -= Time.deltaTime;
}
}
void WaveCompleted()
{
Debug.Log("Wave Completed!");
state = SpawnState.COUNTING;
waveCountdown = timeBetweenWaves;
if (nextWave + 1 > waves.Length - 1)
{
nextWave = 0;
Debug.Log("ALL WAVES COMPLETE! Looping...");
}
else
{
nextWave++;
}
}
bool EnemyIsAlive()
{
searchCountdown -= Time.deltaTime;
if (searchCountdown <= 0f)
{
searchCountdown = 1f;
if (GameObject.FindGameObjectWithTag("Enemy") == null)
{
return false;
}
}
return true;
}
IEnumerator SpawnWave(Wave _wave)
{
Debug.Log("Spawning Wave: " + _wave.name);
state = SpawnState.SPAWNING;
for (int i = 0; i < _wave.count; i++)
{
SpawnEnemy(_wave.enemy);
yield return new WaitForSeconds( 1f/_wave.rate );
}
state = SpawnState.WAITING;
yield break;
}
void SpawnEnemy(Transform _enemy)
{
Debug.Log("Spawning Enemy: " + _enemy.name);
Transform _sp = spawnPoints[ Random.Range (0, spawnPoints.Length) ];
Instantiate(_enemy, _sp.position, _sp.rotation);
}
}
From what I can see is you're also changing the Z position of the bat. Generally you would not want to do that in a 2D game cause it can go behind stuff as is happening there. In the code I did notice that you are using random points in the world so you would want to check the Z position of those points and change them to 0 or 1.Here's the Image of what you need to change on the points! Hope this helps!
I want to display win panel in the game once itemLeft = 0. But still cant figure out how and what is the error about. Below shows my getScore coding:-
public GameObject scoretext;
public GameObject itemlefttext;
public GameObject finalScore;
public static float score = 0;
public GameObject winPanel;
private void Start()
{
scoretext.GetComponent<Text>().text = "0";
setscore(0);
}
private void Update()
{
itemlefttext.GetComponent<Text>().text = "" + GameObject.FindGameObjectsWithTag("draggableobject").Length;
if (GameObject.FindGameObjectsWithTag("draggableobject").Length == 0)
{
winPanel.SetActive(true);
}
}
public void setscore(float scoretoadd)
{
score += scoretoadd;
scoretext.GetComponent<Text>().text = score.ToString("F0");
finalScore.GetComponent<Text>().text = score.ToString("F0");
}
There are many ways to implement this.
With your current code structure:
private void Update()
{
itemlefttext.GetComponent<Text>().text = ""+GameObject.FindGameObjectsWithTag("draggableobject").Length;
//itemLeftTxt = GameObject.FindGameObjectWithTag("Text").GetComponent<Text>();
itemLeftTxt.text = gameObject.GetComponent<Text>().text;
if (itemLeftTxt.text == "0")
{
winPanel.SetActive(true);
}
}
Minor Improvement:
private void Update()
{
itemlefttext.GetComponent<Text>().text = "" + GameObject.FindGameObjectsWithTag("draggableobject").Length;
//itemLeftTxt = GameObject.FindGameObjectWithTag("Text").GetComponent<Text>();
itemLeftTxt.text = gameObject.GetComponent<Text>().text;
if (GameObject.FindGameObjectsWithTag("draggableobject").Length == 0)
{
winPanel.SetActive(true);
}
}
If those draggable objects are not spawned on runtime then you can create a public variable and assign a reference to them through the inspector OR
New way:
public GameObject[] DraggableObjects;
Add this to the start function:
DraggableObjects = GameObject.FindGameObjectsWithTag("draggableobject");
itemLeftTxt = gameObject.GetComponent<Text>();
You can delete extra line of codes:
Final Update function:
private void Update()
{
itemlefttext.text = "" + DraggableObjects.Length;
if (DraggableObjects.Length == 0)
{
winPanel.SetActive(true);
}
}
Final Start Function:
private void Start()
{
DraggableObjects = GameObject.FindGameObjectsWithTag("draggableobject");
itemLeftTxt = GetComponent<Text>();
}
PS: Calling Gameobject.FindGameObjectsWithTag inside the update would be heavy on processor. Let me know if it helps.
I am getting error CS0029 while I was adding a slider to the clicker game to tell how much left you add to buy an item. I am following a YouTube video to learn programming and Unity.
Assets/scripts/UpgradeManger.cs(20,17): error CS0029: Cannot implicitly convert type UnityEngine.UI.Slider[]' toUnityEngine.UI.Slider'
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class UpgradeManger : MonoBehaviour {
public Click click;
public UnityEngine.UI.Text itemInfo;
public float cost;
public float count = 0;
public int clickPower;
public string itemName;
private float basedCost;
public Color standard;
public Color afforable;
private Slider _slider;
void start () {
basedCost = cost;
_slider = GetComponentsInChildren<Slider> ();
}
void Update (){
itemInfo.text = itemName + " (" + count + ")" + "\nCost: " + cost + "/nPower: " + clickPower;
_slider.value = click.gold / cost * 100;
}
public void PurchasedUpgrade() {
if (click.gold >= cost) {
click.gold -= cost;
count += 1;
click.goldperclick += clickPower;
cost = Mathf.Round (cost * 1.15f);
basedCost = Mathf.Pow (cost, basedCost = cost);
}
}
}
[00:41] you're using GetComponentsInChildren instead of GetComponentInChildren
[00:41] GetComponentsInChildren returns an array