I’m having a problem with two scripts (GameMaster.cs and CoinPickUp.cs) that reference each other. The errors that I’m getting on GameMaster.cs is the following: GameMaster.currentScore is inaccessible due its protection level and the name effect does not exist in the current context. That is problem is in CoinPickUp.cs
GameMaster.cs Script
using UnityEngine;
using System.Collections;
public class GameMaster : MonoBehaviour {
static int currentScore = 0;
float offsetY = 40;
float sizeX = 100;
float sizeY = 40;
// Use this for initialization
void OnGUI () {
GUI.Box (new Rect (Screen.width/2 - sizeX/2, offsetY, sizeX, sizeY), "Score: " + currentScore);
}
}
CoinPickUp.cs Script
using UnityEngine;
using System.Collections;
public class CoinPickUp : MonoBehaviour {
Transform coinEffect;
int coinValue = 1;
// Use this for initialization
void OnTriggerEnter (Collider info) {
if (info.tag == “Player”) {
GameMaster.currentScore += coinValue;
int effect = Instantiate (coinEffect, transform.position, transform.rotation);
Destroy (effect.gameObject, 3);
Destroy (gameObject);
}
}
}
I believe member variables will be private by default. Try using the keyword ‘public’.
public static int currentScore = 0;
As SpeakUpGames says, in C# your variables are private unless you explicitly state otherwise, so their code will fix that issue.
As for ‘the name effect does not exist in this context’ error it could be because you have ‘effect’ declared as an integer (int) but are trying to instantiate a transform into it. Try:
Transform effect = Instantiate(coinEffect, transform.position, transform.rotation);
Also, your ‘coinEffect’ transform needs to have something in it for you to instantiate (in Unity, when you instantiate the way you are trying to do you need to tell it what object you are making a copy of by providing the ‘original’. To do this:
- make the prefab public:
public Transform coinEffect;
- select your script in the Unity editor. You’ll notice a blank space now appears in your script in the Inspector called ‘Effect’. Drag-and-drop the prefab you are using for your effect into this empty slot (I’m guessing it’s called coinEffect).
What this does is tell your script what to instantiate a copy of. The ‘effect’ variable will become a copy of the prefab you dragged into your script.
Also note: you probably shouldn’t instantiate and destroy the effect in the OnTriggerEnter method as it’s probably going to impact performance. If you’re just learning I wouldn’t worry too much about it, but remember to read up on ‘object pooling’, which is basically a way to improve efficiency by avoiding instantiating and destroying objects too often (because they are quite slow or ‘expensive’ things to do).