![](/img/trans.png)
[英]Instantiate and apply new PhysicsMaterial2D in script (Unity)
[英]Instantiate a new script?
我知道這很容易,並且如果它是GameObject也可以做到,但是如何實例化新腳本?
Instantiate(FleeScript);
我得到錯誤。
我沒有銷毀和實例化新腳本,而是使用GetComponent.enabled = true / false啟用和禁用它們。
public static void AttachScript(GameObject obj, string scriptClassName)
{
if (obj != null)
obj.AddComponent(scriptClassName);
}
public static void AttachScript(string gameObjectName, string scriptClassName)
{
var obj = GameObject.Find(gameObjectName);
if (obj != null)
obj.AddComponent(scriptClassName);
}
注意:
請記住:腳本必須位於GameObject中。
因此,要獲取新腳本的實例,您可以將其添加到GameObject中:
GameObject myGameObject = ...
FleeScript fleeScript = myGameObject.AddComponent<FleeScript>();
// do something with fleeScript
或者您有一個已經包含該腳本並實例化該預制件的預制件:
public class MyOtherScript
{
public FleeScript prefabWithFleeScript; // Linked from the Editor
void Awake()
{
FleeScript fleeScript= Instantiate(prefabWithFleeScript);
// do something with fleeScript
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.