- Home /
C# script not working
here is a script i put on a trigger collider on my tornado which does the physics for my tornado. there are no errors in the script. but it isnt making my rigidbodies do anything. whats the problem?
Vector3 origin; //Should be set to Tornado's base
[SerializeField]
float tornadoHeight = 40f;
[SerializeField]
float strength = 20f;
[SerializeField]
float accelerationFactor = 1.1f;
[SerializeField]
float yPush = .2f;
List<Rigidbody> entities = new List<Rigidbody>();
float sqrStrength = 400f;
void OnValidate() {
sqrStrength = strength * strength;
}
void FixedUpdate() {
foreach (Rigidbody entity in entities) {
Vector3 relPos = entity.transform.position - origin;
if (relPos.y > tornadoHeight || relPos.x * relPos.x + relPos.z * relPos.z > relPos.y * relPos.y)
continue;
entity.velocity = entity.velocity * accelerationFactor;
float sqrVelocity = entity.velocity.sqrMagnitude;
if (sqrVelocity > sqrStrength)
sqrVelocity = sqrStrength;
float sqrRadius = relPos.sqrMagnitude;
Vector3 radialAcceleration = - relPos * sqrVelocity / sqrRadius;
radialAcceleration.y = radialAcceleration.y + yPush;
entity.AddForce(radialAcceleration);
}
entities.Clear();
}
void OnTriggerStay(Collider other) {
Rigidbody rigidbody = other.gameObject.GetComponent<Rigidbody>();
if (rigidbody != null && !entities.Contains(rigidbody))
entities.Add(rigidbody);
}
}
1st: Dont ever use GetComponent in update or OnTriggerStay constantly
2nd: Use OnTriggerEnter and OnTriggerExit to add and remove your 'List entities'
And if you read the doc: Note: Trigger events are only sent if one of the colliders also has a rigidbody attached. Trigger events will be sent to disabled $$anonymous$$onoBehaviours, to allow enabling Behaviours in response to collisions.
Check if you forgot to add rigidbody to your collider inside the tornado. If it not work, switch to OnCollisionEnter
So what should i use ins$$anonymous$$d of GetComponent?
also if i add a rigidbody to my tornados trigger collider it just falls throgh the ground
rigidbody can have zero gravity or not apply gravity at all.
And like @Ponoveave say get a reference for the rigiidbody at the start and fill it when ontriggerenter, use ontriggerenter so thats called only once
Is your collider marked as trigger? To prevent your tornadoes from fall just remove the gravity from it's rigidbody.
get a reference for the rigiidbody at the start and fill it when ontriggerenter, use ontriggerenter so thats called only once
Answer by NoDumbQuestion · May 20, 2018 at 07:28 AM
And there have already been another answer for this
https://answers.unity.com/questions/753481/ontriggerenter-not-working-tried-everything-c.html
Your answer
Follow this Question
Related Questions
Get result (force & torque) of AddForceAtPosition? 2 Answers
How do I solve this error? 2 Answers
Applying force to an object without rotating it. 2 Answers
Multiple Cars not working 1 Answer
FixedUpdate vs. Update for instantaneous ForceMode's 1 Answer