Hi,
I’m trying input few rigidbody objects in array by tag, and then get the sum of velociy of all objects in array. But it’s not working, error: “velocity is not member of Array.” Here is code:
var allObjects : Array;
var allObjectsVelocity : float;
function Start () {
//input all tagged objects in array
allObjects = GameObject.FindGameObjectsWithTag("Red") + GameObject.FindGameObjectsWithTag("Blue") + GameObject.FindGameObjectsWithTag("Green");
}
function Update () {
//get valocity of multiple object
allObjectsVelocity = allObjects.velocity.magnitude;
print(allObjectsVelocity);
}
Do you have any ideas? Thanks for help.
you have 2 options one is. Store an array of rigidbodies or loop through game objects.
Option 1:
var allObjects : Rigidbody;
function Start()
{
allObjects = new Rigidbody[3];
allOjects[0] = GameObject.FindGameObjectsWithTag("Red").rigidbody;
allOjects[1] = GameObject.FindGameObjectsWithTag("Blue").rigidbody;
allOjects[2] = GameObject.FindGameObjectsWithTag("Green").rigidbody;
}
function Update()
{
float allObjectsVelocity = 0;
foreach(rigid : Rigidbody in allObjects)
{
allObjectsVelocity += rigid.velocity.magnitude;
}
print(allObjectsVelocity);
}
Options 2:
function Update()
{
float allObectsVelocity = 0;
foreach(var go : GameObject in allObjects)
{
allObjectsVelocity += go.rigidbody.velocity.magnitude;
}
print(allObjectsVelocity);
}
The issue is that the return type of allObjects is an Array you need to loop through all of the Array Items to sum the magnitude.
function Update() {
allObjectsVelocity = 0;
foreach(rigid : Rigidbody in allObjects)
{
allObjectsVelocity += rigid.velocity.magnitude;
}
print(allObjectsVelocity);
}
This is not tested and I usually use C# so syntax may not be perfect.
ok, I’m trying but it’s still something wrong. Now the code looks like:
var allObjects : Array = new Array();
var allObjectsVelocity : float;
var i : int;
function Start () {
//input all tagged objects in array
allObjects = GameObject.FindGameObjectsWithTag("Red") + GameObject.FindGameObjectsWithTag("Blue") + GameObject.FindGameObjectsWithTag("Green");
}
function Update () {
allObjectsVelocity = 0;
for (i=0; i<allObjects.length; i++)
{
allObjects *= Rigidbody in allObjects;*
_ allObjectsVelocity += allObjects*.velocity.magnitude;_
_ }*_
print("test velocity : " +allObjectsVelocity);
}
but now I have error : “velocity is not member of object”
Now I think is better and simpler, but problem is now “Cannot cast from source type to destination type”. Do you have any ideas how fix that. Code :
function Update () {
allObjectsVelocity = 0;
for (var rigid : Rigidbody in allObjects)
{
allObjectsVelocity += rigid.velocity.magnitude;
}
print(allObjectsVelocity);
}
Thanks