Trouble Checking A List - c#

Well, it seems I'm re-approaching this problem. What I'm experiencing is, I guess you could say when I "despawn" a monster (the player has killed it), and "respawn" it, it adds all the moves to the list all over again. For example:
Monster A has 2 moves in his list: Scratch & Growl... Monster A dies... Monster A respawns... Monster A now has 4 moves in his list: Scratch & Growl...AND...Scratch & Growl...
Here's my code:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MonsterMoves : MonoBehaviour {
public List<BaseMove> moves;
public int level;
public Scratch scratch = new Scratch();
public Growl growl = new Growl();
public FireBall fireball = new FireBall();
public PowerUp powerup = new PowerUp();
void Start(){
moves = gameObject.GetComponent<Monster>().monstersMoves;
level = gameObject.GetComponent<Monster>().level;
}
void Update(){
level = gameObject.GetComponent<Monster>().level;
SetupMoves(level);
}
private void SetupMoves(int level){
if(level >= 1 && !moves.Contains(scratch)){
moves.Add(scratch);
}
if(level >= 1 && !moves.Contains(growl)){
moves.Add(growl);
}
if(level >= 7 && !moves.Contains(fireball)){
moves.Add(fireball);
}
if(level >= 10 && !moves.Contains(powerup)){
moves.Add(powerup);
}
Any ideas on what I'm over-looking?
To answer some comments:
When the monster dies it's script (just called Monster) calls this:
public void SetDead(){
isAlive = false;
timeOfDeath = Time.time;
ReSpawner.deadMonster.Add(this);
this.gameObject.SetActive(false);
}
This handles "despawning" the monster, without actually destroying it. Then there's THIS script which handles the respawning:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ReSpawner : MonoBehaviour {
public float spawnDistance = 50.0f;
public float minSpawnDensity = 6f;
public float minSpawnDistance = 20f;
public int respawnDelay = 10;
public static List<Monster> deadMonster = new List<Monster>();
private Vector3 spawnPoint;
private Vector3 lastSpawnPoint = Vector3.zero;
void Update(){
for(var i = 0; i < deadMonster.Count; i++){
Monster monster = deadMonster [i];
float time = Time.time - monster.timeOfDeath;
if(time > respawnDelay)
{
monster.gameObject.SetActive(true);
monster.isAlive = true;
monster.gameObject.rigidbody.WakeUp();
monster.gameObject.GetComponent<Animator>().enabled = true;
monster.gameObject.GetComponentInChildren<MonsterAI>().enabled = true;
spawnPoint = new Vector3(Random.Range(0, 2000), Random.Range(0, 2000), Random.Range(0, 2000));
spawnPoint.y = TerrainHeight(spawnPoint);
if(!IsInvalidSpawnPoint(spawnPoint, lastSpawnPoint)){
NavMeshHit closestHit;
if(NavMesh.SamplePosition(spawnPoint, out closestHit, 500, 1)){
spawnPoint = closestHit.position;
}else{
Debug.Log("...");
}
monster.gameObject.transform.position = spawnPoint;
monster.SetupMonster();
deadMonster.RemoveAt(i);
i--;
}
}
}
}
private bool IsInvalidSpawnPoint(Vector3 spawnPoint,Vector3 lastSpawnPoint){
if(spawnPoint.y == Mathf.Infinity || (spawnPoint - lastSpawnPoint).magnitude <= minSpawnDensity){
return true;
}else{
return false;
}
}
private float TerrainHeight(Vector3 spawnPoint){
Ray rayUp = new Ray(spawnPoint, Vector3.up);
Ray rayDown = new Ray(spawnPoint, Vector3.down);
RaycastHit hitPoint;
if(Physics.Raycast(rayUp, out hitPoint, Mathf.Infinity)){
return hitPoint.point.y;
}
else if(Physics.Raycast(rayDown, out hitPoint, Mathf.Infinity)){
return hitPoint.point.y;
}else{
return Mathf.Infinity;
}
}
}
I'm hesitant to post the ENTIRE "Monster" script because it's quite extensive.
SO I'VE MADE SOME CHANGES. Now I call the function whenever the monster is first created, and if/when it levels up. Here's the new script for the MonsterMoves...
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class Moves : MonoBehaviour {
public List<Move> moves;
public List<Move> movesToLearn = new List<Move>();
void Start(){
moves = gameObject.GetComponent<Monster>().monstersMoves;
}
public void AddMoves(int level, List<Move> moves){
foreach(Move move in movesToLearn){
if(level >= move.levelLearned){
if(!moves.Contains(move)){
moves.Add(move);
}
}
}
}
}
I call this function in the script that handles all of the properties of the monster. If the list of Moves already has the move in it, I don't want to add it again. However, it's still not working properly. It's STILL adding the move to the list, even if it's already in there.

Remove monster A from the list before you respawn it!

Related

Why the when playing animation state it's executing the play twice in a row instead once?

The script is attached to empty gameobject
At this line i'm using the mouse left button to fire a bullet one time.
If i'm using a break point it will shot one bullet once. but if i'm not using a break point it will shot two bullets in a row one after the other.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class Shooting : MonoBehaviour
{
public CinemachineVirtualCamera cmf;
[Header("Main")]
public Rigidbody bulletPrefab;
public float launchForce = 700f;
public bool automaticFire = false;
public float bulletDestructionTime;
public bool go = false;
[Space(5)]
[Header("Slow Down")]
public float maxDrag;
public float bulletSpeed;
public bool bulletsSlowDown = false;
public bool overAllSlowdown = false;
[Range(0, 1f)]
public float slowdownAll = 1f;
public List<Transform> firePoints = new List<Transform>();
public Animator anim;
private void Start()
{
if (anim != null)
{
anim.SetBool("Shooting", true);
}
}
public void Update()
{
if (overAllSlowdown == true)
{
Time.timeScale = slowdownAll;
}
if (firePoints.Count > 0))
{
for (int i = 0; i < firePoints.Count; i++)
{
if (Input.GetMouseButton(0))
{
anim.SetTrigger("Shoot");
}
if (Input.GetMouseButton(1))
{
cmf.enabled = false;
}
if (go)
{
LaunchProjectile(firePoints[i]);
go = false;
}
}
}
}
private void LaunchProjectile(Transform firePoint)
{
Rigidbody projectileInstance = Instantiate(
bulletPrefab,
firePoint.position,
firePoint.rotation);
projectileInstance.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
cmf.enabled = true;
cmf.Follow = projectileInstance.transform;
cmf.LookAt = projectileInstance.transform;
projectileInstance.AddForce(new Vector3(0, 0, 1) * launchForce);
if (bulletsSlowDown == true)
{
if (projectileInstance != null)
{
StartCoroutine(AddDrag(maxDrag, bulletSpeed, projectileInstance));
}
}
}
IEnumerator AddDrag(float maxDrag, float bulletSpeed, Rigidbody rb)
{
if (rb != null)
{
float current_drag = 0;
while (current_drag < maxDrag)
{
current_drag += Time.deltaTime * bulletSpeed;
rb.drag = current_drag;
yield return null;
}
rb.velocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
rb.drag = 0;
}
}
}
This script is attached to my player with animator and i'm using this method to reference event i added to animation in the animator controller. when the event happens the variable bool flag go is set to true.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ThrowObject : MonoBehaviour
{
public Shooting shooting;
public void ThrowEvent()
{
shooting.go = true;
}
}
This is a screenshot of the animator controller.
I added a new state name Throwing with two transitions from and to the Grounded state.
The Grounded state is playing idle animation.
In the transition from the Grounded to the Throwing i added a condition name Shoot type trigger.
In the transition from the Throwing state to the Grounded there is no any conditions.
Afaik animator triggers are stackable!
So since you call this in a for loop it might happen that it adds multiple triggers at once but each transition only consumes one at a time!
What I ended up using in combination with triggers in an animator is this script
public class AnimatorTriggerResetter : StateMachineBehaviour
{
override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
foreach(var p in animator.parameters)
{
if (p.type == AnimatorControllerParameterType.Trigger)
{
animator.ResetTrigger(p.name);
}
}
}
}
attach this to no specific state at all but directly to the Basic layer of your AnimatorController itself => It is called for each and every state that is entered => resets all existing triggers.
In your specific case though, why not rather pull the general calls out of the loop and rather make it
if (firePoints.Count > 0 && go)
{
if (Input.GetMouseButton(0))
{
anim.SetTrigger("Shoot");
}
if (Input.GetMouseButton(1))
{
cmf.enabled = false;
}
for (int i = 0; i < firePoints.Count; i++)
{
LaunchProjectile(firePoints[i]);
}
go = false;
}

How can I apply changes for the speed variable also in the Update at run time?

It's working fine in the Start :
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class Waypoints : MonoBehaviour
{
[Header("Objects To Move")]
public Transform objectToMovePrefab;
public int numberOfObjectsToMove = 1;
[Header("Delay At Start")]
public bool useDelay = false;
public bool randomDelayTime = false;
public float delayTime = 3f;
[Header("Movement Speed")]
public float speed = 3f;
public bool randomSpeed = false;
//with this approach, you use GameObjects to represent your waypoints
//(they can be empty if you want the waypoint to be invisible)
[Header("Waypoints")]
[SerializeField] private List<Transform> waypoints;
private List<WaypointsFollower> waypointsFollowers;
[Header("LineRenderer")]
public LineRenderer lineRenderer;
private bool useLineRenderer = true;
private List<Vector3> lineRendererPositions;
[SerializeField] int lineRendererNumOfPositions;
private void Start()
{
for (int i = 0; i < numberOfObjectsToMove; i++)
{
var parent = GameObject.Find("Moving Object Parent");
var objectToMove = Instantiate(objectToMovePrefab, parent.transform);
objectToMove.name = "Platfrom";
}
foreach (GameObject mn in GameObject.FindGameObjectsWithTag("Moving Object"))
{
waypointsFollowers.Add(mn.GetComponent<WaypointsFollower>());
}
StartCoroutine(SendObjectToMove());
}
public int Count => lineRendererPositions.Count;
public Vector3 GetWaypoint(int index)
{
return lineRendererPositions[index];
}
private void Update()
{
if (useLineRenderer && lineRenderer.positionCount > 0 && CurvedLineRenderer.linesSet)
{
lineRendererPositions = GetLinePointsInWorldSpace();
lineRendererNumOfPositions = GetLinePointsInWorldSpace().Count;
foreach(Transform waypoint in waypoints)
{
lineRendererPositions.Add(waypoint.position);
}
useLineRenderer = false;
}
}
private IEnumerator SendObjectToMove()
{
foreach (GameObject mn in GameObject.FindGameObjectsWithTag("Moving Object"))
{
WaypointsFollower waypointsFollower = mn.GetComponent<WaypointsFollower>();
if (useDelay)
{
if (randomDelayTime)
{
yield return new WaitForSeconds(Random.Range(1, 5));
}
else
{
yield return new WaitForSeconds(delayTime);
}
}
if (randomSpeed)
{
waypointsFollower.speed = Random.Range(1, 100);
}
else
{
waypointsFollower.speed = speed;
}
if (waypoints.Count > 0 || lineRendererPositions.Count > 0)
{
waypointsFollower.go = true;
}
else
{
waypointsFollower.go = false;
}
}
}
List<Vector3> GetLinePointsInWorldSpace()
{
var pointsToMove = new Vector3[lineRenderer.positionCount];
//Get the positions which are shown in the inspector
lineRenderer.GetPositions(pointsToMove);
//the points returned are in world space
return pointsToMove.ToList();
}
}
Then on each moving object cloned prefab I added this script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WaypointsFollower : MonoBehaviour
{
[SerializeField] private Waypoints waypoints;
public float speed = 5f;
[SerializeField] private float waypointDistanceThreshold = 0.1f;
[SerializeField] private bool goBack = false;
public bool go = false;
private int waypointIndex = 0;
private void Start()
{
waypoints = GameObject.Find("Waypoints").GetComponent<Waypoints>();
}
void Update()
{
if (go && waypoints.Count > 0)
{
Vector3 waypoint = waypoints.GetWaypoint(waypointIndex);
//movement
float distance = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, waypoint, distance);
//check if we've reached the waypoint
float threshold = waypointDistanceThreshold; //how close is considered having reached the waypoint
if (Vector3.Distance(transform.position, waypoint) < threshold)
{
//wraps back to 0 when we reach last waypoint
if (goBack)
{
waypointIndex = (waypointIndex + 1) % waypoints.Count;
}
else
{
if (waypointIndex != waypoints.Count - 1)
waypointIndex = waypointIndex + 1;
}
}
}
}
}
I can control the speed of each Follower individual but I also want to control the speed of all the Followers from the main Waypoints script and for now I can change the speed in the Inspector and it will affect the changes only in the Start() when starting the game.
How can I make that it will change the speed of all the Followers also in the Update at run time ?
I created a List of all the Followers :
foreach (GameObject mn in GameObject.FindGameObjectsWithTag("Moving Object"))
{
waypointsFollowers.Add(mn.GetComponent<WaypointsFollower>());
}
but not sure how to apply the speed changes in the Update ? Looping in the Update over the Followers each frame is too expensive I guess.
I am not completely sure what you would like to achieve. Well, I know you want to increase the variable Speed on a list of objects that have the component WaypointsFollower(). I suppose what I am confused about is when you want to do this. If Update() is too frequent, what determines when the speed should change?
In your original code, you are using the GameObject.FindGameObjectsWithTag("Moving Object")) too frequently. Only do this once in Awake() or Start(). If any new objects are instantiated, then dynamically add them to the list. Using the FindGameObjectsWithTag frequently can get very expensive. What I am referring to is that you are already storing them, but then in the method SendObjectToMove() you are using it again. Is there a reason you need to call it again in that IEnumartor?
And if you are instantiating these objects on this line
for (int i = 0; i < numberOfObjectsToMove; i++)
{
var parent = GameObject.Find("Moving Object Parent");
var objectToMove = Instantiate(objectToMovePrefab, parent.transform);
objectToMove.name = "Platfrom";
}
Then just store the reference after instantiating them instead of using the FindGameObjectsWithTag.
Here is a very condensed version of your code.
private List<WaypointsFollower> waypointsFollowers;
private void Start()
{
foreach (GameObject mn in GameObject.FindGameObjectsWithTag("Moving Object"))
{
waypointsFollowers.Add(mn.GetComponent<WaypointsFollower>());
}
StartCoroutine(SendObjectToMove());
}
private IEnumerator SendObjectToMove()
{
foreach (WaypointsFollower follwer in waypointsFollowers)
{
// continue your code, but use follower instead of the other object
// you are already storing these objects, so why not reuse them?
}
}
private void UpdateSpeed(float speed)
{
foreach (WaypointsFollower follwer in waypointsFollowers)
{
follower.speed = speed
}
}
I am only using the FindGameObjectsWithTag once in Start() then reusing the list waypointsFollowers it is adding to. I added a function UpdateSpeed that will take a float as a parameter and update every object in the list.

Unity. Help. Created a skiript for the enemy, in which hp decreases for all objects on which it hangs

I'm making a unity shooter. The task was to remove hp from each enemy in its own way.
My code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class monster_animation : MonoBehaviour
{
public GameObject player;
public float dist;
NavMeshAgent nav;
public float Radius = 40f;
public static int health = 100;
// Start is called before the first frame update
void Start()
{
nav = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void Update()
{
if (GameObject.Find("HitEffect(Clone)") != null)
{
health -= 25;
Destroy(GameObject.Find("HitEffect(Clone)"));
}
dist = Vector3.Distance(player.transform.position, transform.position);
if(dist <= Radius)
{
if (dist <= 4)
{
nav.enabled = false;
if (health <= 0)
{
nav.enabled = false;
gameObject.GetComponent<Animator>().SetTrigger("dead");
}
else
{
gameObject.GetComponent<Animator>().SetTrigger("attack");
}
}
else
{
if (health <= 0)
{
nav.enabled = false;
gameObject.GetComponent<Animator>().SetTrigger("dead");
}
else
{
nav.enabled = true;
nav.SetDestination(player.transform.position);
gameObject.GetComponent<Animator>().SetTrigger("run");
}
}
}
if(dist > Radius)
{
nav.enabled = false;
gameObject.GetComponent<Animator>().SetTrigger("idle");
}
}
}
Hang this script on different enemies, after hitting the hp should be taken from a specific enemy, not all.I tried to convert health to static - it didn't help. I made the private variable-it didn't help either. I searched for this answer on the Internet.
As this is not the full code, I assume a few things. Please correct me if I'm wrong.
It seems like you create a HitEffect(Clone) when the bullet hits the enemy, right?
With this approach you the enemy does never know if the HitEffect which was created is next to it or to another player.
It would be easier to do this with physics. Please check on the OnCollisionEnter Function.
This function can be set eather to the enemy or the bullet, (I would do it to the bullet for Class based programming reasons) and check if the other part is a enemy.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class bullet_collision : MonoBehaviour
{
public int damage = 25;
void OnCollisionEnter(Collision collision)
{
monster_animation m = collision.GetComponent<monster_animation>();
if (m != null)
{
m.health -= damage;
}
}
}

Unity How to remove gameobject if they are on same line?

I am making a game like 2 cars. And I have written code to create a instantiater. It is a car game and there are 4 lanes. Let me show you a picture of my game and yeah this is solely for practise.
Player should avoid square objects and eat circle objects but sometimes 2 square objects get spawned in a same lane making impossible for player to win. I have written this script to control that but I failed. Please help me. At least have a check to my DetectSameLaneFunction(). And tell me what I am doing wrong.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour {
public GameObject[] objects;
public float delaytime = 2f; // this is separate for each prefab with which script is attaches
public float spawnrate = 1f; // this is separate for each prefab with which script is attaches
public static int lastgameobjectindex;
public static GameObject lastgameobject;
public static GameObject SecondLastGameObject;
private float loadingtime;
private GameObject go; // just a temporary variable
public static List<GameObject> spawnobjects = new List<GameObject>();
// Use this for initialization
void Start () {
loadingtime = delaytime;
}
// Update is called once per frame
void Update () {
if (Time.time > loadingtime)
{
float randomness = spawnrate * Time.deltaTime;
if ( randomness < Random.value)
{
Spawners();
}
NextLoadTime();
}
}
private void Spawners()
{
int spawnnumber = Random.Range(0, 2);
GameObject go = Instantiate(objects[spawnnumber]) as GameObject;
go.transform.position = this.transform.position;
spawnobjects.Add(go);
Debug.Log(spawnobjects[spawnobjects.Count-1]);
DetectSameLaneObjects();
/* if (spawnobjects.Count > 4)
{
spawnobjects.RemoveAt(0);
}*/
}
private void DetectSameLaneObjects()
{
if (spawnobjects.Count > 3)
{
lastgameobject = spawnobjects[spawnobjects.Count - 1];
SecondLastGameObject = spawnobjects[spawnobjects.Count - 2];
lastgameobjectindex = spawnobjects.Count - 1;
if (SecondLastGameObject.transform.position.x != lastgameobject.transform.position.x
)
{
if (Mathf.Abs(lastgameobject.transform.position.x- SecondLastGameObject.transform.position.x) < 2.3f)
{
Debug.Log("Destroy function getting called");
Destroy(spawnobjects[lastgameobjectindex]);
spawnobjects.RemoveAt(lastgameobjectindex);
}
}
}
}
void OnDrawGizmos()
{
Gizmos.DrawWireSphere(this.transform.position, 0.6f);
}
void NextLoadTime()
{
loadingtime = Time.time + delaytime;
}
}

Unity C# 2d Breakout Clone, Null Reference Exception

Okay so before I begin, Yes I have looked online to find this answer. I've followed advice on multiple other questions, gone through the unity documentation, and done more than a few web searches and nothing I've found so far has solved the error. I'm sure someone will take one look at this and know immediately what's wrong, but as for me, I just can't find it.
Now that that's out of the way Here's the problem. I'm making a Breakout clone and I had everything done, everything working properly. I've got one static class that takes care of the scoring and score related variables, so that other scripts can access them easily. I wanted to practice some basic saving and loading with PlayerPrefs, so I added something for highscores. It's pretty much independent of the other classes, but once I finished that, I started getting a Null Reference Exception in a script that has been done for hours, and was working fine.
I appreciate any help you might have, and any tips for preventing this kind of error the next time around. Sorry It's such a long question.
Here's the full error:
NullReferenceException: Object reference not set to an instance of an object
MenuManager.ActivateLose () (at Assets/Scripts/MenuScripts/MenuManager.cs:31)
Scoring.CheckGameOver () (at Assets/Scripts/Scoring.cs:64)
Scoring.LifeLost () (at Assets/Scripts/Scoring.cs:51)
DeadZone.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/DeadZone.cs:22)
And here are the three scripts listed in said error:
using UnityEngine;
using System.Collections;
public class DeadZone : MonoBehaviour
{
public GameObject ballPrefab;
public Transform paddleObj;
GameObject ball;
void Update ()
{
ball = GameObject.FindGameObjectWithTag("Ball");
}
void OnTriggerEnter2D(Collider2D other)
{
//if the object that entered the trigger is the ball
if(other.tag == "Ball")
{
Scoring.LifeLost();
//destroy it, and instantiate a new one above where the paddle currently is
Destroy(ball);
paddleObj.transform.position = new Vector2(0, -2.5f);
(Instantiate(ballPrefab, new Vector2(paddleObj.transform.position.x, paddleObj.transform.position.y + 0.3f), Quaternion.identity) as GameObject).transform.parent = paddleObj;
}
}
}
using UnityEngine;
using System.Collections;
public static class Scoring
{
public static GameObject scoreValue;
public static TextMesh scoreText;
public static int score;
static int multiplier = 0;
static int consecutiveBreaks = 0;
static int lives = 3;
static int totalBricks;
static int remainingBricks;
public static GameObject menuManagerObj;
public static MenuManager menuManager = new MenuManager();
static void Awake()
{
scoreValue = GameObject.FindGameObjectWithTag("Scoring");
scoreText = scoreValue.GetComponent<TextMesh>();
menuManagerObj = GameObject.FindGameObjectWithTag("MenuManager");
//menuManager = menuManagerObj.GetComponent<MenuManager>();
}
public static void BrickDestroyed()
{
if(scoreValue == null && scoreText == null)
{
scoreValue = GameObject.FindGameObjectWithTag("Scoring");
scoreText = scoreValue.GetComponent<TextMesh>();
}
remainingBricks--;
consecutiveBreaks++;
multiplier = 1 + (consecutiveBreaks % 5);
score += 10 * multiplier;
CheckGameOver();
scoreText.text = score + "";
}
public static void LifeLost()
{
consecutiveBreaks = 0;
multiplier = 1;
score -= 100;
lives--;
LivesDisplay.SetLives(lives);
CheckGameOver();
scoreText.text = score + "";
}
public static void SetBrickCount(int brickCount)
{
totalBricks = brickCount;
remainingBricks = totalBricks;
}
public static void CheckGameOver()
{
//lose condition
if(lives < 0) menuManager.ActivateLose();
//win condition
if(remainingBricks == 0) menuManager.ActivateWin();
}
}
using UnityEngine;
using System.Collections;
public class MenuManager : MonoBehaviour
{
public GameObject winMenu;
public GameObject loseMenu;
public GameObject pauseMenu;
public HighScoreManager highScores;
bool isGamePaused = true;
void Awake()
{
winMenu = GameObject.FindGameObjectWithTag("Win");
loseMenu = GameObject.FindGameObjectWithTag("Lose");
pauseMenu = GameObject.FindGameObjectWithTag("Pause");
}
public void ActivateWin()
{
Time.timeScale = 0f;
winMenu.transform.position = new Vector3(0, 0, -1);
highScores.CompareToHighScores(Scoring.score);
}
public void ActivateLose()
{
Time.timeScale = 0f;
loseMenu.transform.position = new Vector3(0, 0, -1);
}
void ActivatePause()
{
if(isGamePaused)
{
Time.timeScale = 0f;
pauseMenu.transform.position = new Vector3(0, 0, -1);
}
else
{
Time.timeScale = 1f;
pauseMenu.transform.position = new Vector3(35, 0, -1);
}
isGamePaused = !isGamePaused;
}
void Update()
{
if(Input.GetKeyDown(KeyCode.Escape))
{
ActivatePause();
}
}
}
The problem is that Scoring is not a MonoBehaviour so the Awake method never gets called. You can try to initialize the fields in a static constructor
static Scoring()
{
scoreValue = GameObject.FindGameObjectWithTag("Scoring");
scoreText = scoreValue.GetComponent<TextMesh>();
menuManagerObj = GameObject.FindGameObjectWithTag("MenuManager");
//menuManager = menuManagerObj.GetComponent<MenuManager>();
}
or make the Awake method public and call it from another MonoBehaviour.

Categories