私はai fireスクリプトを作成しようとしました。 まず最初に、スクリプトは撮影位置のランダムな2つの番号を作成します。位置を確認するには、軍オブジェクトまたは床オブジェクトがあります。 軍隊のオブジェクトがある場合は、それを破壊するまでのダメージを適用するが、床のオブジェクトがある場合は、それがショットされただけです。AI Fire Script - エラー - GetComponent <ScriptName>().functionName()
NullReferenceException:オブジェクト参照がオブジェクトのインスタンスに設定されていないという問題があります。 エラー行GetComponent()。startEnemyFire();ここで
は、火災スクリプト
public class EnemyFire : MonoBehaviour {
public int min;
public int max;
public static int enemyDamage=2;
public static bool empty;
void Start(){
empty=true;
}
public void startEnemyFire(){
if(empty==true){
Debug.Log("create Position");
createPosition();
}
if(empty==false){
shot();
}
}
public void createPosition(){
min=Random.Range(0,5);
max=Random.Range(0,5);
shot();
}
void shot(){
Vector2 pos=new Vector3(min,max,0);
RaycastHit2D hit = Physics2D.Raycast ((pos), -Vector2.up);
if(hit.collider != null)
{
GameObject target = hit.collider.gameObject;
if(target.tag=="army"){
target.GetComponent<playerArmyMove>().Damaged(enemyDamage);
empty=false;
Debug.Log("army shoted");
}
if(target.tag=="floor"){
target.GetComponent<FloorScript>().changeSprite(enemyDamage);
Debug.Log("floor shoted");
}
}
}
}
、ここでフロアスクリプト
public class FloorScript : MonoBehaviour {
public Sprite damageSprite;
public bool shot =false;
public int hp=1;
public void changeSprite(int value){
if(shot ==true){
GetComponent<EnemyFire>().createPosition(); //Error is here
}
if(shot ==false){
hp-=value;
if(hp <= 0)
{
GetComponent<SpriteRenderer>().sprite = damageSprite;
shot=true;
}
}
}
}
が、私はそれを修正することができた場合、または私はショット位置を保存するための配列を作成し、配列を確認してくださいどのように任意の提案があります愛ポジションはすでに作成済みですか?
頻繁に実行されるコードでは、GetComponent <>を使用しないでください。フィールドを作成し、 'Start()'メソッドで初期化する必要があります。このコンポーネントが他のコンポーネントで使用されている場合は、プライベートセッターでプロパティとして使用します。 –
あなたのアドバイスありがとう、私はそれに取り組む – yatagac