What is a good way to reference instantiated objects from other scripts?

Options

I'm instantiating my player and then instantiating a camera and assigning it to the player. I'm hoping to use the camera attached to the player in another script so that the health bar is facing the same direction as the camera but am having a hard time thinking of a good way to reference the instantiated camera assigned to the player. Any thoughts on a good way to do this?

Best Answer

  • jnchristensen
    Answer ✓
    Options
    Thanks PJB for your reply! I ended up using the namespace and a public getter
    public Transform myCamera
    		{
    			get { return cam; }
    		}
    
    And then to access the camera I use
    [ClassName].instance.myCamera
    
    I believe using the instance of my class accomplishes what I was trying to do.

Answers

  • PJB
    Options
    You could make an accessible manager class and have all your cameras register with it when they instantiate. Pass along any additional information at the same time so code accessing the manager can get what they want.
  • jnchristensen
    Answer ✓
    Options
    Thanks PJB for your reply! I ended up using the namespace and a public getter
    public Transform myCamera
    		{
    			get { return cam; }
    		}
    
    And then to access the camera I use
    [ClassName].instance.myCamera
    
    I believe using the instance of my class accomplishes what I was trying to do.