- Home /
detect Gameobject which is created from c#
hi all
I am not creating GameObject ( Empty object) from UNITY editor instead i am creating new GameObject from C#. I am loading spritesheet and its subimages to these objects. How to detect these objects at runtime ?
I am not able to find which sprite I have clicked. I used RaycastHit2D but its only help if I have a gameobject in editor ( I mean if I have created through Editor). It is not detecting objects which I have created through c# ( as mentioned above).
When I run ( Game mode) I can see newly created sprite and its name since I have added name to object from c#
You should add some of your code with the question, if you don't it's very hard to help. However I believe raycasting requires your GameObject to also have a Collider component attached to it, so when creating the new GameObject are you adding a collider component to it?
I have already posted this http://answers.unity3d.com/questions/1424966/not-able-to-get-clicked-sprite-name-in-this-code.html
Answer by TSI25 · Oct 24, 2017 at 08:21 PM
It sort of depends on how youre creating them, are you just instantiating them as a prefab or are you building a new gameobject from scratch?
make sure it has a collider on there, or you wont be able to detect it with a raycast.
building a new gameobject from scratch the code can be seen here http://answers.unity3d.com/questions/1424966/not-able-to-get-clicked-sprite-name-in-this-code.html
I tried with 2 different ways but not working both ways to get exact gameobject. Always it shows the object which I have created through editor but i am looking for object which i Have created through c#
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction, $$anonymous$$athf.Infinity);
if (hit) {
Debug.Log (hit.transform.name);
}
if (Input.Get$$anonymous$$ouseButtonDown(0)) {
//string tileName = this.GetComponent<SpriteRenderer> ().gameObject.GetComponent<SpriteRenderer> ().sprite.name;
string tileName = GameObject.Find("a2").GetComponent<SpriteRenderer>().sprite.name;
Debug.Log(tileName);
//CastRay();
}