I am new to Unity and C# and I have 26 sprites (prefab) that I am placing on the screen, via code, on top of each other. I have tried without sorting order and with sorting order but get sort of the same result. They all have BoxCollider2D attached.
When i select the sprite on top it is selected some times and some times not.
- Clicked on top (queen) and it was selected and moved
- Clicked on the next sprite (king) that was on top and it got selected, and moved
- Clicked on the next sprite (knight) that was on top and the 9 is selected
The sprites 1 - 3 for the example above:
I do not understand why i am not able to select the card on top, or the one i click on, and would like to get some help. I have been struggling with this problem for many hours. Initially i thought it was a ray cast problem.
The code attached to an empty game object:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class EGOScript : MonoBehaviour {
public static List<string> cardDeckList = new List<string> {
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26",};
public GameObject theGameObject;
float ff = 0f;
public float addIT = 0.01f;
int counter;
// Use this for initialization
void Start () {
counter = 0;
print (cardDeckList.Count);
for (int z = 0; z < 26; z++) {
theGameObject = Resources.Load(cardDeckList[z]) as GameObject;
theGameObject.transform.position = new Vector3(0f + ff, 0f + ff, 80f);
theGameObject.renderer.sortingOrder = counter;
Instantiate(theGameObject);
ff = ff + addIT;
counter++;
}
}
// Update is called once per frame
void Update () {
if(Input.GetMouseButtonDown(0)) {
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if(hit.collider != null) {
print (hit.collider.tag);
}
}
}
}
The code attached to the sprites:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class DragScript : MonoBehaviour {
float x;
float y;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
x = Input.mousePosition.x;
y = Input.mousePosition.y;
}
void OnMouseDrag() {
// Control the drag of the sprite
transform.position = Camera.main.ScreenToWorldPoint (new Vector3 (x, y, 1.0f));
}
}
I also lost control over the camera z-pos so i can’t really see the sprites unless i set the sprites z to 80?
Why is Z-pos on sprites change to -9 when clicked on?
I have also uploaded the test project here: http://www.filedropper.com/unityspritetest2
The “public float addIT” should be set to “0.01f”.
Appreciate all help i can get