参考特定的预制克隆

时间:2016-04-29 10:33:16

标签: unity3d

我正在开发一款简单的2D游戏。在游戏中,我为charcaters创建了一个预制件。我正在改变预制运行时的精灵。这一切都很好。现在我想在特定的预制克隆上应用click事件,并希望增加预制的比例。我附上了我迄今为止所做过的c#脚本。

public class ShoppingManager : MonoBehaviour {

public static ShoppingManager instance;

[System.Serializable]
public class Shopping
{
    public string CharacterName;
    public Sprite CharacterSprite;
}

public GameObject CharacterPrefab;
public Transform CharacterSpacer;

public List<Shopping> ShoppingList;

private CharacterScript NewCharacterScript;

/*********************************************Awake()******************************************/
void Awake()
{
    MakeSingleton ();
}

/******************************Create object of the script**********************************/
void MakeSingleton()
{
    instance = this;
    DontDestroyOnLoad (gameObject);
}

// Use this for initialization
void Start () {
    LoadCharacters ();
}

void LoadCharacters()
{
    foreach (var characters in ShoppingList) {
        GameObject NewCharacter = Instantiate (CharacterPrefab) as GameObject;

        NewCharacterScript = NewCharacter.GetComponent<CharacterScript> ();
        NewCharacterScript.CharacterName = characters.CharacterName;
        NewCharacterScript.Charcater.GetComponent<Image> ().sprite = characters.CharacterSprite;

        NewCharacterScript.GetComponent<Button> ().onClick.AddListener (() => CharacterClicked (NewCharacterScript.CharacterName, NewCharacterScript.Charcater));

        NewCharacter.transform.SetParent (CharacterSpacer, false);
    }
}

void CharacterClicked(string CharacterName, GameObject Char)
{
    StartCoroutine (IncreaseScale (Char));
}

IEnumerator IncreaseScale(GameObject TempCharacter)
{
    int i = 5;
    while (i > 0) {
        yield return new WaitForSeconds (0.1f);

        Vector3 TempVector = TempCharacter.GetComponent<RectTransform> ().localScale;
        TempVector.x = TempVector.x + 0.2f;
        TempVector.y = TempVector.y + 0.2f;
        TempCharacter.GetComponent<RectTransform> ().localScale = TempVector;

        i--;
    }
}

}

此代码会触发点击事件,同时也会增加上一次克隆的比例,而不是点击的预制克隆。我错过了什么,我无法理解。我应该纠正什么呢。是的!我还附上了我在预制件上添加的脚本代码。

public class CharacterScript : MonoBehaviour {

public string CharacterName;
public GameObject Charcater;

}

1 个答案:

答案 0 :(得分:0)

为你的对象创建对撞机将下面的脚本附加到它上面,这样每个对象都负责处理它自己的功能,比如增加它自己的大小

    public class characterFunctionalities: MonoBehaviour{ 
    void OnMouseDown()
    {
        StartCoroutine (IncreaseScale (this.gameobject));
    }

    IEnumerator IncreaseScale(GameObject TempCharacter)
    {
        int i = 5;
        while (i > 0) {
            yield return new WaitForSeconds (0.1f);

            Vector3 TempVector = TempCharacter.GetComponent<RectTransform> ().localScale;
            TempVector.x = TempVector.x + 0.2f;
            TempVector.y = TempVector.y + 0.2f;
            TempCharacter.GetComponent<RectTransform> ().localScale = TempVector;

            i--;
        }
    }
  }