使用来自另一个脚本的变量还是定义它?
Use variable from another script or define it?
我有一个管理器 class,它有很多变量,所以我可以在需要时参考它。
这会降低性能吗?或者我应该定义它
public class Controller: MonoBehaviour
{
public GameObject Manager;
}
public class GetController : MonoBehaviour
{
public GameObject Controller ;
void dosomthing(){
var Ma = Controller.Getcomponent<Controller>().Managet
}
}
TLDR; Getcomponent()
通话费用昂贵。使用的话还可以once/rarely,但是连续调用就开始生效了
存储对它的引用(定义):
public class GetController : MonoBehaviour
{
// Will show up in unity's inspector.
// Drag-and-Drop the gameObject with the 'Controller' component attached to it.
[SerializeField]
private Controller yourController ;
void Dosomthing(){
var Ma = yourController.Manager
}
}
此外,只要是可序列化的,Unity 中的大多数东西都可以暴露给 Inspector。
您可以向检查器公开 Controller
字段,并且 drag-drop 相同的游戏对象。
这让您可以跳过 GetComponent
调用和另一个定义。
我建议对经理使用 singleton
模式。
public class GameManager : MonoBehaviour
{
public static GameManager singleton; // define variable as singleton
public int score = 2; // for example...
private void Start() => singleton = this; // setup single user class instance
}
并且在播放器 class 或任何其他 class 中调用它而不重新定义它。
public class Player : MonoBehaviour
{
public void AddScore() => GameManager.singleton.score += 1; // add score to manager
}
我有一个管理器 class,它有很多变量,所以我可以在需要时参考它。
这会降低性能吗?或者我应该定义它
public class Controller: MonoBehaviour
{
public GameObject Manager;
}
public class GetController : MonoBehaviour
{
public GameObject Controller ;
void dosomthing(){
var Ma = Controller.Getcomponent<Controller>().Managet
}
}
TLDR; Getcomponent()
通话费用昂贵。使用的话还可以once/rarely,但是连续调用就开始生效了
存储对它的引用(定义):
public class GetController : MonoBehaviour
{
// Will show up in unity's inspector.
// Drag-and-Drop the gameObject with the 'Controller' component attached to it.
[SerializeField]
private Controller yourController ;
void Dosomthing(){
var Ma = yourController.Manager
}
}
此外,只要是可序列化的,Unity 中的大多数东西都可以暴露给 Inspector。
您可以向检查器公开 Controller
字段,并且 drag-drop 相同的游戏对象。
这让您可以跳过 GetComponent
调用和另一个定义。
我建议对经理使用 singleton
模式。
public class GameManager : MonoBehaviour
{
public static GameManager singleton; // define variable as singleton
public int score = 2; // for example...
private void Start() => singleton = this; // setup single user class instance
}
并且在播放器 class 或任何其他 class 中调用它而不重新定义它。
public class Player : MonoBehaviour
{
public void AddScore() => GameManager.singleton.score += 1; // add score to manager
}