Search Unity

Access objects attributes from another script

Discussion in 'Scripting' started by v_chs, Jun 18, 2020.

  1. v_chs

    v_chs

    Joined:
    Dec 11, 2019
    Posts:
    64
    I have a script (Script1) that is attached to all of my GameObjects.

    This script has a public dropdown menu (Material) and I need to get this input from another script (Script2) when a collide with an object occurs. So, I need to access the information of the collided object, including the dropdown option (material) that have been selected from the user, from the Script1.

    Code (CSharp):
    1. public class Script1: MonoBehaviour {
    2.    public enum Material {
    3.         First,
    4.         Second,
    5.         Third,
    6.         Fourth
    7.     }
    8. public Material material;
    9. }
    10.  
    11. public Script2: MonoBehaviour {
    12.     private void OnParticleCollision(GameObject collided) {
    13.         // Get collided object material
    14.     }
    15. }
     
  2. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,133
    code not tested, but this is the idea.
    Code (CSharp):
    1. public class Script1: MonoBehaviour {
    2.    public enum Material {
    3.         First,
    4.         Second,
    5.         Third,
    6.         Fourth
    7.     }
    8.  
    9.     public Material material;
    10. }
    11. public class Script2: MonoBehaviour {
    12.     private void OnParticleCollision(GameObject collided) {
    13.         // Get collided object material
    14.         Material matFromScript1 = collided.GetComponent<Script1>().material;
    15.     }
    16. }
     
    v_chs likes this.
  3. v_chs

    v_chs

    Joined:
    Dec 11, 2019
    Posts:
    64
    Thanks for the reply :)

    It works like a charm. Although the Material got me into some bugs because at first imported Unity.Material component :p

    Thanks a lot!
     
  4. v_chs

    v_chs

    Joined:
    Dec 11, 2019
    Posts:
    64
    The only problem I face, is when I call it multiple times, I get error:

    Code (CSharp):
    1. NullReferenceException: Object reference not set to an instance of an object
     
  5. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,133
    I Will need to see more of the code. What line is the error happening on?
     
    v_chs likes this.
  6. v_chs

    v_chs

    Joined:
    Dec 11, 2019
    Posts:
    64
    I figured out the solution. thnx anyway! :)