- Home /
Problem accessing child GameObjects
Hello, I need to change the value of a variabile from another script. Here is the code I'm using:
playerPrefab.GetComponentsInChildren(true)[0].allWeapons[0]=(WeaponScript)transform.Find("BallisticKnife");
In other words I need to change the allWeapon[0] value with a gameobject (child of PlayerPrefab) called "BallisticKnife". The type of BallisticKnife is "WeaponScript". The problem is that unity report an error:
error CS0030: Cannot convert type
UnityEngine.Transform' to >
WeaponScript'
Any help please ? Many thanks !
Answer by Adamcbrz · Jun 04, 2013 at 05:09 PM
If i understand your question correctly you need to not use get component once you find the object.
transform.Find("BallisticKnife").GetComponent<WeaponScript>();
Answer by Jessy · Jun 04, 2013 at 05:10 PM
Transform.Find returns a transform. You don't cast a Transform to the type of your script. Get the Component you need attached to the transform.
GetComponentsInChildren(true) doesn't mean anything. Your code doesn't convey meaning. You should try rewriting it again to do so. We can help.
GetComponentsInChildren(true) works because in Unity 4.0 the GetComponentsInChildren() function is a bit different than the one in 3.x .. Infact "playerPrefab.GetComponentsInChildren(true)[0].allWeapons[0]" works perfectly ...
Voted down for lying or not testing your code. GetComponentsInChildren(true) doesn't work, because it conveys no meaning. You're not telling it what component to look for. Assigning to the first element of that array conveys no meaning. Convey meaning.
Jessy, ins$$anonymous$$d of downvoting read the last post here: http://forum.unity3d.com/threads/154093-Strange-NullReferenceException .. Then please stop to reply this question. Thanks.
Sorry Luca91 but you just proved his point (not trying to be rude).
o.GetComponentsInChildren<ShipNavigator>(true)[0];
This includes a type of ShipNavigator while yours doesn't include a type. But I think you would have received that error once you resolve the transform error. Which I address in my original answer.
oh God you are right ! In the working line of code I've a type! Well, thanks $$anonymous$$for pointing this out. Also, Jessy sorry it was my fault then ;)
EDIT: the correct code was:
playerPrefab.GetComponentsInChildren<Weapon$$anonymous$$anager>(true)[0].allWeapons[0];
:)
Your answer
Follow this Question
Related Questions
Deploy object avoiding collisions 0 Answers
How to delay a line of code. 2 Answers
transform.parent can't go with gameObject.find 3 Answers
How to reactivate a gameObject? 3 Answers
Cannot conver UnityEngine.Transform to UnityEngine.GameObject 3 Answers