- Home /
How do I instantiate certain objects to appear in a specific spot?
Although the picture below is a little glitchy, I want to be able to instantiate those three cylinders after I click on the object onMouseDown. I want to be able to have those three cylinders in the exact position and alignment as on the object. How do I do that?
Also, how would I return to just the single main object (the tree) if I want to. I'm not sure how to implement something like that either.
Am I supposed to create prefabs and instantiate those?
Thanks!
Answer by HappyMoo · Dec 31, 2013 at 09:03 PM
Build your hierarchy like this:
Tree
Cylinders
Cylinder1
Cylinder2
Cylinder3
Then put a collider on the Tree. This will define what you can click. You get most precision if it's a mesh collider, but maybe a capsule collider is enough - you decide.
Cylinders is an empty gameObject(CTRL+SHIFT+N)
Then add the ClickSwitch MonoBehaviour to Tree and drag Cylinders in the obj reference and you're good to go.
public class ClickSwitch : MonoBehaviour {
public GameObject obj;
void OnMouseDown() {
obj.SetActive(!obj.activeSelf);
}
}
That makes me think, how do I set only my gameobjects active= false then set them true when the user clicks on it?
Thanks.
Can you specify exactly what you want? Click on the tree switches visibility of the cylinders?
I'm getting this error: Error CS1061: 'UnityEngine.Transform' does not contain a definition for 'setActive' and no extension method 'setActive' accepting a first argument of type 'UnityEngine.Transform' could be found (are you missing a using directive or an assembly reference?) (CS1061) (Assembly-CSharp)
You're getting that error because you don't enable the Transform, you enable the gameObject. change
public Transform obj; to public GameObject obj;
Answer by DaveA · Dec 31, 2013 at 08:36 PM
I think you would use this:
http://docs.unity3d.com/Documentation/ScriptReference/Physics.Raycast.html
using one of the ones that returns the 'hit' information. That will contain the point at which the object was hit, and the normal at that point too in case you need it.
Prefabs are good. That way if you want to change what you are placing there you just change the prefab.
Answer by J-R-Wood · Jan 26, 2014 at 07:47 PM
I think this is probably already answered, but if not. have you thought of doing like a instiate object on collision, and have that as the place to instiate at. or do a on collision and have that as the game object to setactive