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

GetComponent from script

Discussion in 'Scripting' started by Raybrand, Apr 3, 2014.

  1. Raybrand

    Raybrand

    Joined:
    Feb 6, 2012
    Posts:
    98
    Code (csharp):
    1.  
    2. var Weilder1 : GameObject;
    3. var Weilder2: MonoScript;
    4. var Weapon;
    5.  
    6. function Start () {
    7. Weapon = Weilder1.GetComponent(Weilder2);
    8. }
    I want to be able to use get component from scripts but I want to be able to change the script in the inspector, that way the same script can be used on multiple objects rather than make multiple scripts. But Im getting an error with the
    Code (csharp):
    1. Weapon = Weilder1.GetComponent(Weilder2);/CODE]
    2. line.
    3. it says
    4. "BCE0018: The name 'Weilder2' does not denote a valid type ('not found')."
     
  2. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    For what purpose are you trying to do this?

    It's likely that polymorphism or an interface will be a better choice.
     
  3. Cooper37

    Cooper37

    Joined:
    Jul 21, 2012
    Posts:
    383
    Take away the Weapon =.
     
  4. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    What? No - that wouldn't do anything.

    You're using the variable Weilder2 in GetComponent when you should be using MonoScript which is the Type and assigning the result to Weilder2 (assuming that's what you're trying to do).
     
  5. Raybrand

    Raybrand

    Joined:
    Feb 6, 2012
    Posts:
    98
    This script is applied to the enemy weapon,

    weilder2 represents the character that has the weapon equipped

    weilder1 represents the enemy ai script, in this script it tells the weapon when to be active, sets its attack strength

    this way I can have 10 different enemy types with different scripts all using this one script for their weapon.

    so far, all enemies that use the same script can use the same script for their weapons because weilder2 can be assigned to the appropriate gameobject. I want to expand this to enemies with different AI scripts
     
    Last edited: Apr 3, 2014