- Home /
Unity 3.5 C# Problem
This is a similar question to the last one. Since i couldnt figure out JavaScript for Flash i decided to try it in C#... Im not good at c#. Here is my script
using UnityEngine;
using System.Collections;
public class PlayerWeapons : MonoBehaviour {
void Start () {
SelectWeapon(0);
}
void Update () {
if(Input.GetKeyDown("1")){
SelectWeapon(0);
}
if(Input.GetKeyDown("2")){
SelectWeapon(1);
}
}
void SelectWeapon(int index){
For(int i=0; i<Transform.childCount; i++)
{
if(i == index)
Transform.GetChild(i).gameObject.SetActiveRecursively(true);
if(i != index)
Transform.GetChild(i).gameObject.SetActiveRecursively(false);
}
}
}
And here are the errors
Unexpected symbol
i', expecting
.'Only assignment, call, increment, decrement, and new object expressions can be used as a statement
Unexpected symbol
)', expecting
;'Parsing error
Any help is appreciated
Answer by BerggreenDK · Dec 24, 2011 at 11:05 PM
Its around the statement with the FOR loop.
My first guess is that you need to spell FOR with small-caps. Not For but for
Secondly, you could try to make your IF-THEN structure a bit easier for yourself.
Here is the function if I should write it:
void SelectWeapon(int index)
{
for(int i=0; i<transform.childCount; i++)
{
transform.GetChild(i).gameObject.SetActiveRecursively(i == index);
}
}
Notice that I use the result of the comparison as the value for the SetActiveRecursively(bool)
If you prefered the IF structure you could do it like this:
void SelectWeapon(int index)
{
for(int i=0; i<transform.childCount; i++)
{
if(i == index)
{
transform.GetChild(i).gameObject.SetActiveRecursively(true);
}
else
{
transform.GetChild(i).gameObject.SetActiveRecursively(false);
}
}
}
One problem here is the two errors that still appear. The rest is excellent though.
An object reference is required to access non-static member UnityEngine.Transform.childCount' An object reference is required to access non-static member
UnityEngine.Transform.GetChild(int)'
Transform
is a class name. Therefore it doesn't belong to a specific Transform instance. To access the Transform component of the gameobject where this script is attached to you have to use `transform` (lower case) which is a shortcut property of your script to access the Transform component of this object.
The usual way to get a reference to any other component on this GameObject is to use GetComponent
GetComponent<Transform>()
// is the same as
transform
edit
I've edited the answer to correct the T
. It should work now ;)
thanks for specifying that detail Bunny! $$anonymous$$uch appriciated.
Your answer
