使用1个脚本Unity将bool设置为不同的对象

时间:2015-06-06 02:22:38

标签: c# unity3d

我在google上阅读了很多页面以及我能找到的其他所有内容,但没有任何帮助我,所以我必须在这里问:我将脚本附加到100个立方体上,它说:

using UnityEngine;
using System.Collections;
public class IfClose:MonoBehaviour{

  public bool Gravitronned=false;

  // Use this for initialization
  void Start(){
  }

  // Update is called once per frame
  void Update(){
  }

  void OnTriggerEnter(Collider col)
  {
    if(col.gameObject.name =="IfInScreenGrv"){
      Gravitronned=true;
    }
    else
    {
      Gravitronned=false;
    }
  }
}

然后我有另一个脚本说:

using UnityEngine;
using System.Collections;
public class TimeFreeze:MonoBehaviour{

  static bool GravitronedTwice;

  // Use this for initialization
  void Start(){
  }
  void Update()
  {
    GravitronedTwice= gameObject.GetComponent<IfClose>().Gravitronned;
    if(GravitronedTwice=true){
      if(Input.GetKeyDown(KeyCode.V)){
        Physics.gravity =newVector3(0,3.0F,0);
      }
    }
  }
}

所以当我按 V 时,我希望仅在此区域内的多维数据集得到Physics.gravity = new Vector3 (0, 3.0F, 0);

enter image description here

1 个答案:

答案 0 :(得分:0)

你使用GetComponent&lt;&gt;()调用第二个脚本中的bool变量Gravitronned的值,这不是解决此问题的正确方法。

如果没有两个bool变量,Gravitronned和GravitronnedTwice,你只需要在第一个脚本中有一个变量,将它公开[尽管将它公开为一个坏主意 - 但这是另一个主题]并让它访问两个脚本,而不是你正在做的。这样你就可以改变bool值,并在两个脚本中访问它。

或者,您可以在脚本1中使bool Gravitronned为private,并通过C#属性在任何其他脚本中访问它。 脚本1

private bool Gravitronned;

public BOOL GRAVITY
{
  get Gravitronned;
  set Gravitronned;
}