Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

[Solved] Prefab Instance Communication with other GameObjects

Discussion in 'Scripting' started by Afrodeity, Dec 19, 2015.

  1. Afrodeity

    Afrodeity

    Joined:
    Dec 19, 2015
    Posts:
    12
    So, I'm stuck implementing a little puzzle mechanic, but for the sake of brevity I'll only explain the issue I've identified. I use the Material mat of my Gun Controller gc to swap r.material and rHit.material.

    Code (CSharp):
    1. Renderer rHit = hit.collider.gameObject.GetComponent<Renderer>();
    2. gc.mat = rHit.sharedMaterial;
    3. rHit.material = r.sharedMaterial;
    4. if (hits < 1){
    5.     Destroy(gameObject);
    6.     return;
    7. }
    8. r.material = gc.mat;
    Assigning a material to the gun controller material gc.mat isnt a problem, but when I try to verify it in the gun controller script, the material is equal to null. I test this using this code:

    Code (CSharp):
    1. if(mat != null) Projectile.GetComponent<Renderer>().material = mat;
    2. else print ("I am a failure.");
    3. Instantiate(Projectile, SpawnPoint.transform.position, Quaternion.Euler(0, 0, 0));
    This is a problem because the material of the next Projectile I'll instatiate is not what I want it to be. These are my two questions: What causes Material mat to be null when I call it in my Gun Controller and what can I change to correctly assign my new material?
     
  2. Afrodeity

    Afrodeity

    Joined:
    Dec 19, 2015
    Posts:
    12
    I finally found a solution! The problem was caused by having two different instances of my GunController. As such, the material of the actual GunController is never assigned. All I had to do was to get the GunController-component of the gun itself:
    Code (CSharp):
    1. gc = transform.GetComponentInParent<GunController>();
    In my case I referenced the parent, since I also required the angle of the gun.