Quantcast
Channel: Questions in topic: "attach"
Viewing all articles
Browse latest Browse all 168

How to get a parent object after clicking the childObject

$
0
0
Hi guys.I am a novice to unity. I tried to create a 2D top-down game and I came across a few problems; I want to attach a button to a block object, so I stored these two into an object called pairs. Each pairs object has two properties which are references to a block and a button. I want to create multiple pairs objects in random time and each time I click the button, it will disappear and the block will disappear after 10 seconds. Firstly, I tried to use **OnGUI()** to draw the button, but it seems to be very difficult since the position of the GUI button is not as the same in the world view and I could't figure out how to continuously add button in the **OnGUI** function since I don't know when a pairs object will be created. So I tried to make the button object a cube, and it's easy to bind a cube to block, and I can add textures to the button cube as button text.After clicking the button object, I want to destroy the block object attached to it, but I don't know how to get the block object. I tried like this:**Destroy(hit.collider.gameObject.transform.parent.GetChild(1),10F);** It appears that I could't have access to these objects. but it looks like it didn't work. So I am looking for help now. Below are my codes: public class createObject : MonoBehaviour { List obstacles = new List(); List obstaclesPos = new List(); void running (){ Pairs zhu = new Pairs ("car"); obstacles.Add (zhu); obstaclesPos.Add (zhu.blockPos); } void Start() { InvokeRepeating ("running", 5F,5F); } void Update (){ if(Input.GetMouseButtonDown(0)){ RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if(Physics.Raycast(ray, out hit)){ Destroy(hit.collider.gameObject,10F); Destroy(hit.collider.gameObject.transform.parent.GetChild(1),20F); } } } } and here is the pairs class: public class Pairs{ public GameObject block; public GameObject button; public Vector3 blockPos; public string typeName; public Pairs(string typeName){ this.blockPos = new Vector3 (Random.Range(-5f, 5f), Random.Range(-5f, 5f), 1); this.button = GameObject.CreatePrimitive (PrimitiveType.Cube); this.button.transform.position = new Vector3 (this.blockPos.x + 2, this.blockPos.y, 1); this.typeName = typeName; switch (typeName) { case "car": this.block = GameObject.CreatePrimitive (PrimitiveType.Capsule); break; } this.block.transform.position = this.blockPos; UnityEngine.Object.Destroy(this.block.GetComponent()); } }

Viewing all articles
Browse latest Browse all 168

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>