永远不会调用脚本中的方法

时间:2015-12-05 17:32:32

标签: c# unity3d

我有一个附加到GameObject的Projectile脚本。现在我想从附加到GameObject A的脚本A访问Projectile脚本中的LinearProjectile()方法。这里我在脚本A中创建了一个类型为Projectile的公共字段,并传入一个连接了Projectile脚本的GameObject。

要访问我刚刚做过的LinearProjectile()方法。

projectile.LinearProjectile(transform.position, transform.rotation, this.direction, this.shotPower);
//Here is my method defination..

public void LinearProjectile(Vector3 position, Quaternion rotation, Vector2 direction, float force)
{
    Debug.Log("called");
    this.direction = direction;
    this.force = force;
    this.projectileType = ProjectileType.Linear;
}

此方法中指定的所有字段值都处于默认状态,因为从不调用此方法。如何从其他GameObject脚本访问此方法。 我尝试了GetComponent()。方法(),但即使我无法访问这里的错误是什么?我花了很多时间找出但没有成功..帮助我

2 个答案:

答案 0 :(得分:2)

提供了这样的场景:

  • 我们在场景中有GameObject,我们称之为Item
  • 我们已将ProjectileScript附加到Item
  • 我们在A
  • 附加了Item脚本

我们需要做的就是调用A脚本:

gameObject.GetComponent<ProjectileScript>().LinearProjectile();

如果它位于另一个GameObject,我会亲自在A脚本中创建要在Inspector中使用的字段,例如:public GameObject ProjectileScriptHolder,然后只需拖动{{1}从包含GameObject的场景到ProjectileScript中的变量并以此方式访问:

Inspector

我还会在调用方法之前检查每个ProjectileScriptHolder.GetComponent<ProjectileScript>().LinearProjectile(); 因为它可能返回null,即:

GetComponent<T>

如果您无法通过ProjectileScript script = ProjectileScriptHolder.GetComponent<ProjectileScript>(); if (script != null) script.LinearProjectile(); 附加项目,则可以使用Inspector并在场景中找到FindWithTag(),只要其附加了GameObjectTagFindWithTag()作为参数,并在场景中查找带有此类标记的string

答案 1 :(得分:0)

我知道你想从另一个游戏对象上的另一个脚本访问脚本!

方式1

有一种简单的方法可以缓存脚本。 (假设脚本的名称是:“ProjectileScript”)

在ScriptA上创建一个

public ProjectileScript pS;

你需要初始化它,有两种方法: 1-在GameObjectA的检查器上,使用projectileScript拖动GameObject。

2.1-如果脚本在同一个游戏对象中:

pS = GetComponent<ProjectileScript> ();

2.2-如果它在另一个游戏对象上,你可能需要以某种方式找到这个对象。考虑使用标签

 pS = GameObject.FindGameObjectWithTag("projectile").GetComponent<"ProjectileScript">(); 

并将其投入脚本A:

pS.LinearProjectile();

方式2

或者您可以使用ProjectileScript在GameObject上创建一个通用标记并找到它:

GameObject.FindGameObjectWithTag("projectile").GetComponent<"ProjectileScript">.LinearProjectile();

这对你有意义吗?对不起我的英文。

相关问题