尝试从另一个脚本访问变量

时间:2018-12-18 08:47:21

标签: visual-studio unity3d

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Projectile : MonoBehaviour  
{

    Weapon weapon;

    void Start()
    {
        Weapon weapon = GameObject.Find("Thing").GetComponent<Weapon>();
    }

    void Update()
    {

    }

    void OnTriggerEnter(Collider other)
    {
        other.gameObject.GetComponent<EnemyHealth>().TakeDamage(weapon.damage);
        Destroy(gameObject);
    }
}

1 个答案:

答案 0 :(得分:0)

您再次声明该武器,它在本地范围内被分配,但是一旦您离开方法主体,就会被垃圾收集器吞噬。只需用武器替换武器武器,这将告诉编译器您正在访问现有变量而不创建一次性变量

尝试使用“开始”代替

    void Start()
    {
     var thing=GameObject.Find("Thing");
     if (thing==null) Debug.Log("Thing object not found");
      else
      {   
         weapon = thing.GetComponent<Weapon>();
         if (weapon==null) 
        Debug.Log("No weapon found on thing;
      }
    }