Accessing boolean from a different class in C# - c#

I have one collision script in which I set a boolean to true or false
using UnityEngine;
using System.Collections;
public class IsTriggerLockCamera : MonoBehaviour {
public bool CameraLock = false;
public void OnTriggerStay2D(Collider2D other) {
CameraLock = true;
Debug.Log ("Im inside");
}
public void OnTriggerExit2D(Collider2D other) {
CameraLock = false;
Debug.Log ("I exited");
}
}
I want to access this boolean from my camera script, I tried this
if (CameraLock == true) {
Debug.Log ("Im locked");
}
However, I get an error saying that CameraLock doesn't exist in the current context. The boolean is public so I'm very confused.
EDIT: I feel like I didn't give good enough info so I'll start by posting the whole camera script and then clarifying.
using System;
using UnityEngine;
public class CameraFollowLockY : MonoBehaviour
{
public Transform target;
public float damping = 1;
public float lookAheadFactor = 3;
public float lookAheadReturnSpeed = 0.5f;
public float lookAheadMoveThreshold = 0.1f;
private float m_OffsetZ;
private Vector3 m_LastTargetPosition;
private Vector3 m_CurrentVelocity;
private Vector3 m_LookAheadPos;
private void Start()
{
m_LastTargetPosition = target.position;
m_OffsetZ = (transform.position - target.position).z;
transform.parent = null;
}
private void Update()
{
float xMoveDelta = (target.position - m_LastTargetPosition).x;
bool updateLookAheadTarget = Mathf.Abs(xMoveDelta) > lookAheadMoveThreshold;
if (updateLookAheadTarget)
{
m_LookAheadPos = lookAheadFactor*Vector3.right*Mathf.Sign(xMoveDelta);
}
else
{
m_LookAheadPos = Vector3.MoveTowards(m_LookAheadPos, Vector3.zero, Time.deltaTime*lookAheadReturnSpeed);
}
Vector3 aheadTargetPos = target.position + m_LookAheadPos + Vector3.forward*m_OffsetZ;
Vector3 newPos = Vector3.SmoothDamp(transform.position, aheadTargetPos, ref m_CurrentVelocity, damping);
transform.position = newPos;
transform.position = new Vector3(transform.position.x, 0, transform.position.z);
m_LastTargetPosition = target.position;
if (CameraLock == true) {
Debug.Log ("Im locked");
}
}
The IsTriggerLockCamera is a script I used for an invisible collider in Unity. My camera is focused on the player at all times, but I want it to stop moving when the player is close to reaching the edge of the map, so he can notice that the map is ending. The original plan was, that the collider would send out information when player enters it and then instead of Debug.Log ("Im Locked"); would be some code that would lock the camera in place. I don't know if this solution is very elegant and I'd like to apologize for not clarifying everything properly beforehand, but I started coding probably 2 months ago (I did only Rails websites) and I got into C# game development about a week ago so I'm still missing the terminology required to properly describe the problems I encounter. So far, no suggestion has worked. The closest working suggestion was OnoSendai's suggestion, but apparently it's not allowed to create MonoBehaviour using "new".
Edit2: Making the boolean static didn't work at first, but then I realized that I had to make some changes in my camera script as well, so it works now, but Philip said that it's a bad advice - I personally have no idea why, I assume that it's something like using !important in CSS, you just use it as a last resort because it makes the code not that flexible - so I'm still open to ideas.

You may want to try a full reference to the CameraLock property based on the object instance - as in
var objRef = new IsTriggerLockCamera(); // Just an example of object reference -
// You may already have one
// on your code.
if (objRef.CameraLock) {
Debug.Log ("Im locked");
}
That happens because CameraLock is marked as public, but not as static - it only exists on a instantiated object.

If your camera needs access to the IsTriggerLockCamera then dependency injection is good way to make it clear :
class Camera{
private readonly IsTriggerLockCamera _locker;
public Camera(IsTriggerLockCamera locker){
if (locker== null)
{
throw new ArgumentNullException("locker");
}
_locker = locker;
}
public void whatevermethod(){
if (_locker.CameraLock){
...
}
}
}

You need to set the variable you want to access from other scripts, static as well as public.
using UnityEngine;
using System.Collections;
public class IsTriggerLockCamera : MonoBehaviour {
public static bool CameraLock = false;
public void OnTriggerStay2D(Collider2D other) {
CameraLock = true;
Debug.Log ("Im inside");
}
public void OnTriggerExit2D(Collider2D other) {
CameraLock = false;
Debug.Log ("I exited");
}
}
Then you can access CameraLock :
if (CameraLock == true) {
Debug.Log ("Im locked");
}

I would like to suggest some approach,
Make CameraLock variable as protected.
Create a new class and make IsTriggerLockCamera class as base class.
consume the CameraLock variable and work on it.
Thanks,

C# has a function called { get; set } that you can use with a variable
This program is an example
Static Type
public static class AYO
{
public static string Variable1 { get; set; }
}
public class B
{
public void LOL()
{
string foo;
AYO.Variable1 = "Variable is now set";
foo = AYO.Variable1;
Console.WriteLine(foo);
}
}
Non Static
public class AYO
{
public string Variable1 { get; set; }
}
public class B
{
AYO ayo = new AYO();
public void LOL()
{
string foo;
ayo.Variable1 = "Variable is now set";
foo = ayo.Variable1;
Console.WriteLine(foo);
}
}

Related

C# Unity; Sending a variable to a method as a pointer/reference or similar instead of whatever value the variable has

I am trying to make a script that will display the direction of a force with an arrow. The arrow is a GameObject that is initialized at startup. Upon initialization the public static GameObject ForceArrowBase is set to the object that already exists. This object is then instantiated when calling CreateNewForceArrow.
The forceVector in the ForceArrow class should not be a value, but rather some sort of reference/pointer or something in that nature. So when forceArrow.forceVector = forceVector is being called in the CreateNewForceArrow method, it shouldn't set the value to be whatever the value is at that point in time. Rather, it should set it to refer to the part of the memory that holds the variable data of the caller.
So when WindForce's Wind.Data.Speed changes, the forceVector in the ForceArrow refers to the data point Wind.Data.Speed.
In a way, it would be: void ForceVector { get => Wind.Data.Speed; }. But of course, if the CreateNewForceArrow method was called by ForceCreatingScript2, then it should be: void ForceVector { get => instancedForceCreatingScript2.forceOutput; }
So, is there anyway to parse the variable in as a pointer-type-thingy rather than the value of the variable?
public class ForceArrow : MonoBehaviour {
public static GameObject ForceArrowBase;
private static bool _initialized = false;
public GameObject refObject;
public Vector3 forceVector;
public float force;
public void FixedUpdate() {
transform.rotation = Quaternion.LookRotation(forceVector);
}
public static void CreateNewForceArrow(string name, ref Vector3 forceVectorReference, GameObject forceObject) {
var forceArrowObject = Instantiate<GameObject>(ForceArrowBase);
var forceArrow = forceArrowObject.GetComponent<ForceArrow>();
forceArrowObject.transform.position = forceObject.transform.position;
forceArrowObject.gameObject.name = name + "_forceArrow";
forceArrow.forceVector = forceVectorReference;
forceArrow.refObject = forceObject;
}
}
public class ForceCreatingScript1 : MonoBehaviour {
public Vector3 forceVector;
void Start() {
ForceArrow.CreateNewForceArrow(name, ref forceVector, gameObject);
}
void FixedUpdate() {
forceVector *= 1.2f;
}
}
public class ForceCreatingScript2 : MonoBehaviour {
public Vector3 forceOutput;
void Start() {
ForceArrow.CreateNewForceArrow(name, ref forceOutput, gameObject);
}
void FixedUpdate() {
forceOutput *= 1.6f;
}
}
public class WindForce : MonoBehaviour {
void Start() {
ForceArrow.CreateNewForceArrow(name, ref Wind.Data.SpeedVector, gameObject);
}
void FixedUpdate() {
Wind.Data.Speed = Mathf.Clamp(Wind.Data.Speed + Wind.WindRandom(), 15, Wind.MaximumWindSpeed);
Wind.Data.SpeedVector = BISH_MathHelper.DegreeToVector3(Wind.Data.DegAngle);
Wind.Data.RadAngle = (Wind.Data.RadAngle + Wind.WindRandom() / 80f) * Mathf.Rad2Deg;
}
}
Thanks for any help!

Unity C# How to reference a subscript in another script?

In the following script, I get the error "Inaccessible due to protection level.":
public class WrongAnswerScript : MonoBehaviour
{
void OnMouseDown()
{
GetComponent<Renderer>().material.color = Color.red;
GameManager.UpdateMistakes(1);
}
}
Here is the code of the GameManager class which manages the update:
public class GameManager : MonoBehaviour
{
public List<GameObject> targets;
public TextMeshProUGUI mistakeText;
public int mistakes;
void Start()
{
mistakes = 0;
mistakeText.text = "Mistakes: " + mistakes;
}
// Update is called once per frame
void UpdateMistakes(int mistakesToAdd)
{
mistakes += mistakesToAdd;
mistakeText.text = "Mistakes: " + mistakes;
}
}
How should I correctly initiate my script ? I am pretty new to C# so I struggle to understand the basics.
make the function public so that it becomes accessible.
public void UpdateMistakes(int mistakesToAdd)
You might need to make sure that you reference an existing instance of the GameManager that is somewhere in your scene.
private bool HasBeenClicked = false;
void OnMouseDown()
{
GetComponent<Renderer>().material.color = Color.red;
//Only do this block when you have not clicked before
if (!HasBeenClicked)
{
//get a reference to the gamemanager that is already somewhere in the scene
GameManager gameManager = (GameManager)FindObjectOfType(typeof(GameManager));
gameManager.UpdateMistakes(1);
HasBeenClicked = true;
}
}

Unity3D - enemy not taking damage

In Unity3D my enemy is not taking damage upon colliding with my projectile explosion.
Although this is not the case as it the health variable is unaffected upon colliding with my projectile explosion.
My Enemy and Barrel classes inherit from Entity which handles the taking of damage (subtracting the damage variable from the health variable). Although only the barrel class is working as intended.
The tags are 100% correct and I would prefer to continue using inheritance so please no suggestions to change the method in which my classes take damage.
the class that Enemy and Barrel inherit from
using UnityEngine;
using System.Collections;
public class Entity : MonoBehaviour {
public float health = 25;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public virtual void takeDamage(float dmg){
health -= dmg;
if (health <= 0){
Destroy(this.gameObject);
}
}
}
Enemy class
using UnityEngine;
using System.Collections;
public class Enemy : Entity {
private NavMeshAgent agent;
public GameObject target;
// Use this for initialization
void Start () {
agent = GetComponent<NavMeshAgent> ();
}
// Update is called once per frame
void Update () {
agent.SetDestination (target.transform.position);
}
}
Barrel class
using UnityEngine;
using System.Collections;
public class Barrel : Entity {
private Transform myTransform;
//Effects
public GameObject barrelExplosion;
public GameObject explosionDamage;
public GameObject explosionSound;
// Use this for initialization
void Start () {
myTransform = this.transform;
}
// Update is called once per frame
void Update () {
}
public override void takeDamage(float dmg){
health -= dmg;
if (health <= 0){
Instantiate(barrelExplosion, myTransform.position, myTransform.rotation);
Instantiate(explosionSound, myTransform.position, myTransform.rotation);
Instantiate(explosionDamage, myTransform.position, myTransform.rotation);
Destroy(this.gameObject);
}
}
}
ExplosionAOE the class that sends the damage
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ExplosionAOE : MonoBehaviour {
public float damage = 100.0f;
public float lifeTime = 0.05f;
private float lifeTimeDuration;
public List<GameObject> damageTargets = new List<GameObject>();
public float radius = 15.0f;
GameManager gameManager;
void Start() {
gameManager = GameObject.FindGameObjectWithTag("GameManager").GetComponent<GameManager>();
//Destroy (this.gameObject, lifeTime);
lifeTimeDuration = Time.time + lifeTime;
transform.GetComponent<SphereCollider>().radius = radius;
}
void Update() {
//Explosion finishes, damage targets and remove AOE field
if (Time.time > lifeTimeDuration) {
foreach (GameObject target in damageTargets) {
if (target != null) {
//Calculate damage based on proximity to centre of explosion
float thisDamage = ((radius - Vector3.Distance(target.transform.position, transform.position)) / radius) * damage;
print(thisDamage);
target.GetComponent<Entity>().takeDamage(thisDamage);
//target.SendMessage("takeDamage", damage); //<< This is not good code. Let's fix this!
}
}
Destroy(this.gameObject);
}
}
void OnTriggerEnter(Collider otherObject) {
if (otherObject.gameObject.tag == "Enemy") {
damageTargets.Add(otherObject.gameObject);
}
if (otherObject.gameObject.tag == "Player") {
Vector3 jumpVector = (otherObject.transform.position - transform.position).normalized;
jumpVector *= 25;
otherObject.GetComponent<CharacterMotor>().SetVelocity(jumpVector);
}
}
}
Sorry this is a bit of a lengthy one and EVERYTHING is tagged correctly so that is not the issue, thanks.
Problem 1.
Use "Debug.Log" everywhere
void OnTriggerEnter(Collider otherObject) {
Debug.Log("in trig");
Debug.Log("otherObject.gameObject.tag is " + otherObject.gameObject.tag);
if (otherObject.gameObject.tag == "Enemy") {
Debug.Log("a");
damageTargets.Add(otherObject.gameObject);
}
if (otherObject.gameObject.tag == "Player") {
Debug.Log("b");
Vector3 jumpVector = (otherObject.transform.position -
transform.position).normalized;
jumpVector *= 25;
otherObject.GetComponent<CharacterMotor>().SetVelocity(jumpVector);
}
}
In particular, in Entity and Enemy.
Questions such as this one are instantly answered by tracking with Debug.Log.
Problem 2.
It's a PITA getting the relationships between triggers, rigidbody, etc.
It's very likely that's a problem here.
http://docs.unity3d.com/Manual/CollidersOverview.html
Go down to the annoying "trigger action matrix" and work from there.
Problem 3.
As a rule, never use the "tags" feature in Unity. (They only added tags to help "hello world" tutorials.)
In practice you use layers everywhere and always:
(Layers are particularly essential in shooting games: every single category needs a layer.)
Problem 4.
The code shown is definitely looking good. Here's some example code not unlike yours for tips.
Trivial example, note the breakaway code (the returns) inside the OnTrigger, you should do that).
Also,
use extentions
everywhere and always in Unity. Quick tutorial
it's the #1 tip if you actually want to work professionally.
public class Enemy:BaseFrite
{
public tk2dSpriteAnimator animMain;
public string usualAnimName;
[System.NonSerialized] public Enemies boss;
[Header("For this particular enemy class...")]
public float typeSpeedFactor;
public int typeStrength;
public int value;
// could be changed at any time during existence of an item!
[System.NonSerialized] public FourLimits offscreen; // must be set by our boss
[System.NonSerialized] public int hitCount; // that's ATOMIC through all integers
[System.NonSerialized] public int strength; // just as atomic!
[System.NonSerialized] public float beginsOnRight;
private bool inPlay; // ie, not still in runup
void Awake()
{
boss = Gp.enemies;
}
..........
protected virtual void Prepare() // write it for this type of sprite
{
ChangeClipTo(bn);
// so, for the most basic enemy, you just do that.
// for other enemy, that will be custom (example, swap damage sprites, etc)
}
void OnTriggerEnter2D(Collider2D c)
{
// we can ONLY touch either Biff or a projectile. to wit: layerBiff, layerPeeps
GameObject cgo = c.gameObject;
if ( gameObject.layer != Grid.layerEnemies ) // if we are not enemy layer....
{
Debug.Log("SOME BIZARRE PROBLEM!!!");
return;
}
if (cgo.layer == Grid.layerBiff) // we ran in to Biff
{
Gp.billy.BiffBashed();
// if I am an enemy, I DO NOT get hurt by biff smashing in to me.
return;
}
if (cgo.layer == Grid.layerPeeps) // we ran in to a Peep
{
Projectile p = c.GetComponent<Projectile>();
if (p == null)
{
Debug.Log("WOE!!! " +cgo.name);
return;
}
int damageNow = p.damage;
Hit(damageNow);
return;
}
Debug.Log("Weirded");
}
public void _stepHit()
{
if ( transform.position.x > beginsOnRight ) return;
++hitCount;
--strength;
ChangeAnimationsBasedOnHitCountIncrease();
// derived classes write that one.
if (strength==0) // enemy done for!
{
Gp.coins.CreateCoinBunch(value, transform.position);
FinalEffect();
if ( Gp.superTest.on )
{
Gp.superTest.EnemyGottedInSuperTest(gameObject);
boss.Done(this);
return;
}
Grid.pops.GotEnemy(Gp.run.RunDistance); // basically re meters/achvmts
EnemyDestroyedTypeSpecificStatsEtc(); // basically re achvments
Gp.run.runLevel.EnemyGotted(); // basically run/level stats
boss.Done(this); // basically removes it
}
}
protected virtual void EnemyDestroyedTypeSpecificStatsEtc()
{
// you would use this in derives, to mark/etc class specifics
// most typically to alert achievements system if the enemy type needs to.
}
private void _bashSound()
{
if (Gp.biff.ExplodishWeapon)
Grid.sfx.Play("Hit_Enemy_Explosive_A", "Hit_Enemy_Explosive_B");
else
Grid.sfx.Play("Hit_Enemy_Non_Explosive_A", "Hit_Enemy_Non_Explosive_B");
}
public void Hit(int n) // note that hitCount is atomic - hence strength, too
{
for (int i=1; i<=n; ++i) _stepHit();
if (strength > 0) // biff hit the enemy, but enemy is still going.
_bashSound();
}
protected virtual void ChangeAnimationsBasedOnHitCountIncrease()
{
// you may prefer to look at either "strength" or "hitCount"
}
protected virtual void FinalEffect()
{
// so, for most derived it is this standard explosion...
Gp.explosions.MakeExplosion("explosionC", transform.position);
}
public void Update()
{
if (!holdMovement) Movement();
if (offscreen.Outside(transform))
{
if (inPlay)
{
boss.Done(this);
return;
}
}
else
{
inPlay = true;
}
}
protected virtual void Movement()
{
transform.Translate( -Time.deltaTime * mpsNow * typeSpeedFactor, 0f, 0f, Space.Self );
}
......
/*
(frite - flying sprite)
The very base for enemies, projectiles etc.
*/
using UnityEngine;
using System.Collections;
public class BaseFrite:MonoBehaviour
{
[System.NonSerialized] public float mpsNow;
// must be set by the boss (of the derive) at creation of the derive instance!
private bool _paused;
public bool Paused
{
set {
if (_paused == value) return;
_paused = value;
holdMovement = _paused==true;
if (_paused) OnGamePause();
else OnGameUnpause();
}
get { return _paused; }
}
protected bool holdMovement;
protected virtual void OnGamePause()
{
}
protected virtual void OnGameUnpause()
{
}
protected string bn;
public void SetClipName(string clipBaseName)
{
bn = clipBaseName;
}
}
Is more easy if in ExplosionAOE/OnTriggerEnter function you call the takeDamage function:
scriptCall = otherObject.GetComponent(EnemyScript);
scriptCall.takeDamage(damage);

C# UNITY Instantiate Class (Create Object) without using new operator

example I have class name "PlayerClass" and "StatClass"
PlayerClass
public float health = 100 ;
public float experience;
StatClass
PlayerClass playerclass = new PlayerClass()
public float health2;
public float experience2;
health2 = playerclass.health;
experience2 = playerclas.experience;
usually I have to create "PlayerClass playerclass = new PlayerClass()"
the result will be the same health2 and experience2;
but whenever i made a change on healt from player class with code of course, the result healt2 from StatClass will be the same it was 100
Sory for my bad english.
----------------- Edited -----
GameControl
public class GameControl : MonoBehaviour {
public static GameControl control;
public float health = 100;
public float experience = 1000;
// Use this for initialization
void Awake () {
/*
* Awake Start Before Start() Happen
*/
if (control == null) {
DontDestroyOnLoad (gameObject);
control = this;
} else if (control != this) {
Destroy (gameObject);
}
}
}
GetHealth
public class GetHealth : MonoBehaviour {
public static GetHealth getHealth;
GameControl gameControl = new GameControl();
//GameControl gameControl;
public static float health;
Text text;
void Awake () {
/*
* Awake Start Before Start() Happen
*/
if (getHealth == null) {
DontDestroyOnLoad (gameObject);
getHealth = this;
} else if (getHealth != this) {
Destroy (gameObject);
}
text = GetComponent<Text> ();
health = 0;
}
void Update(){
health = gameControl.health;
text.text = "Health: " + health;
}
}
I made Change on value variable Health in GameControl. but Get Health always access 100 the same as first time when variable GameControl haven't changed. I think it was maybe because we use "new" on GetHealth class.
GameControl gameControl = new GameControl();
Is there another way to solve this without "new".
If instantiation of player was in updateStat method and it is calling in void update() method, it cause to instantiate player object again and again. You can try this or instantiate playerclass2 in constructor. Also making health and experience static will help if only player object exist.
Class StatClass{
PlayerClass playerclass2;
public float health2;
public float experience2;
public void updateStat(){
if(playerclass2==null) playerclass2 = new PlayerClass();
health2 = playerclass2.health;
experience2 = playerclas2.experience;
}
}
EDIT
You can't use new keyword since it is derived from MonoBehavior. Have to use ClassName.method() format to call methods of derived classes from MonoBehavior
Thanks all, I have Found it.
It just have to
health = GameControl.control.health;
I don't have to instantiate it I just Call class and then initialize of class and then variable of class.

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