mardi 20 octobre 2020

Give other class reference to current class instance

i am working in unity and i will try to breakdown my problem so that non unity people can also help me.

I just want to have a link to the TrackPart instance in the class StartSelectColliderHelper in order to modify values for Trackpart from StartSelectColliderHelper. My version does not work. I think i am at a point where i need a specific design pattern but i don't know which one. In my version tp ist null when OnTriggerEnter is called.

    //TrackPart.cs
    public class TrackPart
    {
        string data; //contains data
        public void CreateSelectCollider()
        {
            startSelectCollider = new GameObject("StartSelectCollider");
            StartSelectColliderHelper SSCHelper = startSelectCollider.AddComponent<StartSelectColliderHelper>();
            SSCHelper.SaveTrackPartAlias(this);
        }
    
        public string getData()
        {
            return data;
        }
    }
    //end file
//StartSelectColliderHelper.cs
public class StartSelectColliderHelper : MonoBehaviour
{
    private TrackPart tp;

    public void SaveTrackPartAlias(TrackPart tp)
    {
        this.tp = tp;
    }

    private void OnTriggerEnter(Collider other)
    {
        
        if(other.name == "SphereRightHand")
        {
            if (tp != null)
            {
                Debug.Log("in StartSelectColliderOntriggerEnter...");
                tp.trackPart.GetComponent<MeshRenderer>().material.color = Color.red;
            }
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire