• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Catsby · Jan 03, 2011 at 08:28 PM · gameobjectsstudent

Learning how to use Game Objects

Hey everyone,

I'm slowly learning how to use game objects but I'm running into some problems. To help illustrate the questions I want to ask here's a short script attached to a object called "HUD".

var partymember1 : GameObject; var partymember2 : GameObject; var pmember1switch : boolean = true;

function OnGUI(){

 if (pmember1switch == true){

     var pmember1win = GUI.Window (0, Rect(50, 50, 80, 70), 
         pmember1button , "Select party member1:");
 }

 var punchbutton = GUI.Window (1, Rect(100, 50, 80, 70),
         punch, "Click");

}

function pmember1button (windowID){

     var SoldierSelect = GUI.Button(Rect(10, 25, 60, 20), "Soldier");

     if (SoldierSelect == true){

         Debug.Log("Soldier was selected");
         partymember1 = new GameObject ("PartyMember1");
         partymember1.AddComponent("Soldier");
         pmember1switch = false;
     }

     var MedicSelect = GUI.Button(Rect(10, 45, 60, 20), "Medic");

     if (MedicSelect == true){

         Debug.Log("Medic was selected");
         partymember1 = new GameObject ("PartyMember1");
         partymember1.AddComponent("Medic");
         pmember1switch = false;
     }

} // the following function doesn't work
function punch(windowID){

     var punchpmember = GUI.Button(Rect(10, 25, 60, 50), "Punch!");

     if (punchpmember == true){

         partymember1.HP = partymember1.HP -1;
     }       

}

So here we have a window with 2 buttons on it and when either is clicked a new character is selected for a party member slot and a corresponding script is attached(suppose we are making group oriented RPG or a strategy game). This is just an example so the Soldier and Medic scripts only have 1 line in them; var HP : int = 100;

The first question is, how do I access functions and variables in the new game object like I'm trying to do in the punch function? Obviously we wont know which character is selected until the player makes a decision so referencing a specific script wont help. I've read about a messaging system but I've also noticed some people saying it's inefficient. I'm pretty sure this has been answered before but I spent a long time wading through unityAnswers and found tons of examples similar but not exact enough to help so I figured I would just ask.

The second question is, if I wanted to do character selection for a much more complex game are there better ways to do it than this example? (suppose you want to be able to save your game, add dozens of different characters, have multiple functions in the character scripts, carry character parameters from one scene to another).

Thanks a ton!

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Catsby · Jan 03, 2011 at 08:29 PM 0
Share

dawww... forgot to use that partymember2 var but I guess it lends itself to question 2.

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by Loius · Jan 03, 2011 at 09:42 PM

Use inheritance to make all characters damageable -

class Character extends Monobehaviour { var hp : int; var job : Job; function Damage( amount : int ) { hp-= amount; }

}

class Medic extends Character { } class Soldier extends Character { }

Now both Medic and Soldier objects can be used like -

partyMember1.GetComponent(Character).Damage(1);

Since Soldier is a Character and has all the functions and properties of a chractare.

Use arrays and enums for extendability -

var partyMembers : List.<Character>; // a list of all party members

private var currentMember : int; // which member we're choosing a job for

// All possible jobs - enums are lists of integers that can be referenced by name for readability purposes enum Job { Soldier, Medic,

max // for ease of use in loops } // String names for the jobs private var jobNames : String[] = ["Soldier", "Medic"];

private var jobTypes : Type[] = [Soldier, Medic]; // these would be the names of the scripts you'll add to the new objects

function OnGUI() { // display a button for each job for ( var job : int = 0; job < Job.max; job++ ) { if ( GUILayout.Button( jobName[ job ] ) ) { AddPartyMember( job ); } }

// Display a health / damage button for each member who's had a job chosen for ( var member : int = 0; member < partyMembers.length; member++ ) { var health = partyMembers[member].hp; job = jobName[ partyMembers[member].job ]; if ( GUILayout.Button( member + ": " + job + ": " + health ) ) { partyMembers[member].Damage(1); } } }

function AddPartyMember( job : Job ) { Debug.Log("Adding new " + jobNames[job] + " as member " + currentMember );

// create a new game object named Party Member X var newMember : GameObject = new GameObject("Party Member " + currentMember);

// a Job is an integer (that's how enumerations (enums) work), and jobTypes is a list of each job class as it corresponds to the jobs in the enum Job // that is - // jobTypes[ Job.Soldier ] is equal to "Soldier" (or Soldier, depending on how that needs to be set up) // jobTypes[ Job.Medic ] is equal to Medic // Whatever job gets passed in to this function will then be added to the new party member newMember.AddComponent( jobTypes[ job ] ); // Now, since we are the programmer, we know that all jobTypes extend Character // (that is, "class Soldier extends Character" and "class Medic extends Character") // And we can get the just-added component, no matter what it is, since we know it's a Character // Get that Character component and change its job and hp to the desired values var c : Character = newMember.GetComponent( Character ); // ideally this would be handled in some kind of Initialize function per class, but for simplicity's sake here ya go c.job = job; switch( job ) { case Job.Soldier: c.hp = 100; break; case Job.Medic: c.hp = 75; break; } // partyMembers is an array of Characters - we can add c to it because c is a Character (even though c might also be a medic or soldier) partyMembers.Add( c ); // adds the new character to our list currentMember++; Debug.Log("Success."); }

You can then add Save, Load, etc functions to Character and every Medic and Soldier will have access to those (in addition to its own).

Comment
Add comment · Show 17 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Catsby · Jan 03, 2011 at 10:32 PM 0
Share

wow thanks. So you have a class called characters that extends monobehaviour and then you put all job parameters there? What's the benefit of putting it all together versus having separate scripts for each job?

I'll try to find more on enums and what you do with them.

avatar image Loius · Jan 04, 2011 at 12:00 AM 0
Share

With separate scripts (that don't inherit) you have to say ("if soldier, else if medic, else if dude, else if priest,") etcetera. If the functions they all share (damage, attack, moveto) are in one class, you remove a lot of that iffing and it's far easier on you the programmer. :)

avatar image Catsby · Jan 04, 2011 at 05:33 PM 0
Share

Just wondering if there is a Javascript equivalent to the List you declared at the very beginning of your second code example.

avatar image Catsby · Jan 04, 2011 at 07:48 PM 0
Share

arg I thought I knew what I was doing but all these arrays are confusing me.

avatar image Loius · Jan 04, 2011 at 08:36 PM 0
Share

List. is a javascript equivalent for C#'s generics (if you have unity 3.x; otherwise you'll have to settle for Array, which isn't as good since it lacks type safety) I agree the arrays can get confusing but I find that keeping the variable names very clear (jobNames, etc) can help make them not so confusing. I also use UnityDevelop (you can find it on the forum) which has lots of headache-preventing features that Unity's default scripters don't seem to have.

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

No one has followed this question yet.

Related Questions

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

Can someone help me fix my Javascript for Flickering Light? 6 Answers

Setting Scroll View Width GUILayout 1 Answer

Material doesn't have a color property '_Color' 4 Answers

How to make a character bounce? 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges