Hello everyone. The title pretty much explains it all. I'm trying to reference the player's lives in my game in multiple scripts to make multiple things happen if it hits zero, but I keep getting errors in scripts that reference it. It's like Unity is only letting me use GetComponent on it once, then it won't work anymore. By the way, I'm trying to get a script and use it's playerlives variable/score variable. I tried static at first, but then the static variables are stuck that way and won't reset if the player presses the restart button. Here are 2 of my scripts; the first has the problems, the second works fine. By the way, the script component I'm referencing is called "PlayerData."
using System.Collections;
public class Endless : MonoBehaviour {
private Transform myTransform;
public float minspeed = 1f;
public float maxspeed = 10f;
public float currentspeed;
int x,y,z;
// Use this for initialization
void Start () {
myTransform = transform;
currentspeed = Random.Range(minspeed, maxspeed);
x = Random.Range (-10, 10);
y = 8;
z = -1;
myTransform.position = new Vector3 (x,y,z);
}
// Update is called once per frame
void Update () {
myTransform.Translate (Vector3.down * currentspeed * Time.deltaTime);
if (myTransform.position.y <= -8) {
x = Random.Range (-10, 10);
currentspeed = Random.Range (minspeed, maxspeed);
myTransform.position = new Vector3 (x, 8, z);
Instantiate(myTransform, new Vector3(x, 8, z), Quaternion.identity);
}
}
void OnTriggerEnter (Collider collider){
GameObject PlayerData = GameObject.Find ("PlayerData");
PlayerData playerdata = PlayerData.GetComponent ("PlayerData");
//if laser hits enemy, destroy enemy
if(collider.gameObject.CompareTag("Laser")){
Instantiate(myTransform, new Vector3(x, 8, z), Quaternion.identity);
Destroy (gameObject);
}
if (collider.gameObject.CompareTag ("Player")) {
playerdata.score += 50;
//Unity denies this and gives this msg: Assets/Scripts/Endless.cs(37,28): error CS0266: Cannot implicitly convert type `UnityEngine.Component' to `PlayerData'. An explicit conversion exists (are you missing a cast?)
Destroy(this.gameObject);
}
}
//Script that works with GetComponent
using UnityEngine;
using System.Collections;
public class MyGUI : MonoBehaviour {
// Use this for initialization
void Start () {
//how to call an unstatic component from another gameobject
//in this case, I called it's script component so I could reference nonstatic variables.
//GameObject PlayerData = GameObject.Find ("PlayerData");
//PlayerData playerdata = PlayerData.GetComponent ("PlayerData");
}
// Update is called once per frame
void Update () {
}
void OnGUI () {
GameObject PlayerData = GameObject.Find ("PlayerData");
PlayerData playerdata = PlayerData.GetComponent ("PlayerData");
GUI.Box (new Rect (700, 25, 300, 100), "Score : " + playerdata.score + " Lives: " + playerdata.playerlives);
}
}
Sorry if the question is confusing. All help is appreciated!
↧