我有以下用于管理Unity中某些粒子系统物理的C#脚本:
//PS Variables
ParticleSystem myPS;
public List<ParticleCollisionEvent> collisisonEvents;
//Physics variables
public float effect;
// Use this for initialization
void Start () {
myPS = GetComponent<ParticleSystem>();
collisisonEvents = new List<ParticleCollisionEvent>();
}
void OnParticleCollision (GameObject other)
{
//Checking if the hit object is indeed the ball
bool isBall = other.tag.Equals("Player");
if (isBall)
{
Rigidbody2D hitObject = other.GetComponent<Rigidbody2D>();
//Getting the number of collisions that have occured this frame
int numOfCollisions = myPS.GetCollisionEvents(other, collisisonEvents);
Vector3 particleDirection = new Vector2(0,0);
//Iterating through all the events
for (int i = 0; i < numOfCollisions; i++)
{
//Calculating a resultant direction
particleDirection += collisionEvents[i].velocity;
}
//Applying the resultant force
hitObject.AddForce(particleDirection.normalized * effect * numOfCollisions);
}
}
然而, collisionsEvents 列表的范围似乎存在问题,因为我无法在OnParticleCollision协同例程中的for循环中使用它。我继续得到“当前上下文中不存在collisionsEvents”的错误。变量myPS虽然没有这个问题,但它与collisionsEvents在同一个地方声明。
有人可以帮我吗?
答案 0 :(得分:3)
你拼错了变量名。在声明中,您使用collisisonEvents
并使用方法collisionEvents
。
问题不在于范围。如果你在类级别声明它,编译器只会在输入拼写错误时抱怨不存在。
虽然我不得不承认,这些事情有时难以发现;)