我想从HarmEnemiesScript更改playerCurScore整数(在ScoreManager脚本中)。
(附加到场景中的对象的脚本)
using UnityEngine;
using System.Collections;
public class ScoreManager : MonoBehaviour
{
public int playerScore;
public int playerCurScore;
public void Start()
{
playerScore = 0;
playerCurScore = 0;
}
public void Update()
{
playerCurScore = playerScore;
}
}
(附在敌人身上的脚本)
using UnityEngine;
using System.Collections;
public class HarmEnemies : MonoBehaviour
{
public float enemyHealth;
public float enemyCurHealth;
public float playerDamage;
public void Start()
{
enemyCurHealth = enemyHealth;
}
public void OnTriggerEnter(Collider theCollision)
{
if(theCollision.tag == "Fireball")
{
enemyCurHealth = enemyCurHealth - playerDamage;
Destroy (theCollision);
}
if(enemyCurHealth <= 0)
{
Destroy (this.gameObject);
}
}
}
那么如何从HarmEnemies更改playerCurScore Int。我知道我必须使用GetComponent,我可以使用playerCurScore ++;
答案 0 :(得分:0)
你犯了几个错误。主要的一点是ScoreManager
脚本不应附加到EnemyGameObject
。
制作一个单独的GameObject并将其命名为ScoreManager
。然后在场景中找到它并更新分数。
ScoreManager s = GameObject.Find("ScoreManager");
s.SendMessage("incrementScore", amount);
在ScoreManager课程中,你需要这个:
private static int score;
public void incrementScore(int amount)
{
score += amount;
}
如果你聪明,你可以制作整个ScoreManager课程static
,然后它甚至不必是MonoBehaviour
。
然后你会这样称呼它:
ScoreManager.incrementScore(amount);
有关static classes的信息。
答案 1 :(得分:0)
我现在可以修复它,谢谢你的静态提示。我的代码现在看起来像这样:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ScoreManager : MonoBehaviour
{
public static float playerScore;
public Text scoreCount;
public void Update()
{
ScoreController ();
}
public void ScoreController()
{
scoreCount.text = "Score: " + playerScore;
Debug.Log ("Score: " + playerScore);
}
}
using UnityEngine;
using System.Collections;
public class HarmEnemies : MonoBehaviour
{
public float enemyHealth;
public float enemyCurHealth;
public float playerDamage;
public void Start()
{
enemyCurHealth = enemyHealth;
}
public void OnTriggerEnter(Collider theCollision)
{
if(theCollision.tag == "Fireball")
{
enemyCurHealth = enemyCurHealth - playerDamage;
Destroy (theCollision);
}
if(enemyCurHealth <= 0)
{
ScoreManager.playerScore = (ScoreManager.playerScore + 1);
Destroy (this.gameObject);
}
}
}