Stealing enemies points in multiplayer game

139 views Asked by At

I have a "Player" gameObject that spawn OnServerInitialized(). It's tag "Enemy" change to "Player" when GetComponent<NetworkView>().isMine.

I'd like to make something like:

void OnTriggerEnter (Collider Enemy){ 
    if (ScoreManager.score > Enemy.Score) {
            ScoreManager.score = ScoreManager.score + Enemy.Score;
    }
    else if (ScoreManager.score < Enemy.Score) {
Destroy (gameObject);
    }
}

But I don't know how to access to spawned enemy player's points.

My ScoreManager Script:

public static int score;

Text text;

void Awake () {
    text = GetComponent <Text> ();
    score = 0;  
}
void Update () {    
    text.text = "Score: " + score;
 }
}

It is attached to GUI text gameObject named ScoreText.

1

There are 1 answers

0
RaidenF On

1)when you're using GetComponent always check for null.

2)Don't use GetComponent. Serialize the variable (or make it public) by addding [System.Serializable] above Text text; and drag and drop in the inspector, the text component.

3)You don't have to refresh the score every frame, only when it changes. This should be done using events.

In order to access the enemy's points, you can use GameObject.FindWithTag, and use the "Enemy" provided that the enemy has this tag. You can get a reference to the enemy game object that way. Then access its score component.

For example:

ScoreManager enemyScoreManager = null;
GameObject enemyReference = GameObject.FindWithTag("Enemy");
if (enemyReference !=null)
    enemyScoreManager = enemyReference.GetComponent<ScoreManager>();
if (enemyScoreManager != null)
{
    enemyScoreManager.score -=5; //steal 5 points
    myScore.score +=5; //assuming myScore is a reference to your score manager
}
else
    Debug.LogError("Enemy not found");