简体   繁体   中英

Set bool to different objects with 1 script Unity

I read many pages on google and everything else I could find but nothing helped me, so I have to ask here: I made a script attached to 100 cubes it says:

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;
    }
  }
}

and then I have another script that says:

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);
      }
    }
  }
}

so when I press V I want the cube only in this area to get Physics.gravity = new Vector3 (0, 3.0F, 0);

在此处输入图片说明

You're calling the value of the bool variable Gravitronned in the second script using GetComponent<>() which is not the right way of going about this.

How about instead of having two bool variables, Gravitronned and GravitronnedTwice, you only have 1 variable in the first script, make it public [even though make it public a bad idea - but that's another topic altogether] and have it access to both the scripts, instead of what you're doing. That way you can change the bool value, as well as access it in both scripts.

Alternatively, you can make the bool Gravitronned private in Script 1, and access it in any other script via C# property. Script 1

private bool Gravitronned;

public BOOL GRAVITY
{
  get Gravitronned;
  set Gravitronned;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM