(Unity) How can I programmatically make Array Elem

2019-09-19 13:24发布

问题:

I have Array Elements I got them on an Empty GameObject, I mean [SerializeField] and added through the script (C# Ofcourse), So the Objects are not really there they are being Generated when the Game begins. How can I clone the Collider from the Empty GameObject onto the clones in order to make them clickable? So far as of right now only the first one works witch is also the possition of the empty GameObject who has the colider on it now I need them onto the Clones as well... but,...How?

I tried to apply the collider to the sprites I even tried turning them into Prefab Its All hopeless. I do think It has to be on the script but I cannot find a code example of it....

public class Controll : MonoBehaviour {
public const int gridRows = 6;
public const int gridCols = 6;
public const float offsetX = 1.70f;
public const float offsetY = 0.97f;

[SerializeField] private GameObject[] cardBack;
[SerializeField] private GameObject[] positioner;

public AudioSource sound;

public void OnMouseDown()
{

    if (Input.GetMouseButtonDown(0))
    {
        sound.Play();
    }
}

//AudioSource audioSource;



// Use this for initialization
void Start ()
{
   // audioSource = GetComponent<AudioSource>();

    Vector3 startPos = positioner[0].transform.position;
    for (int i = 0; i < gridRows; i++)

    {
        for (int j = 0; j < gridCols; j++)
        {

            var position = transform.position + new Vector3(offsetX * j, offsetY * i * -1, -0.1f);
            Instantiate(cardBack[i], position, Quaternion.identity, transform);
        }
   }
}

I need to be able to click on these elements so they be playing a sound when i click and disappear....

回答1:

I figured out a solution...

@ BugFinder I had cut out the function "on mouse down" and pasted it onto a separated script with just that function and applied that to all the prefabs while the other script with all other functions has stayed on the game-object. So that seems to work well so far.....