• 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 Sareh Shadowborne · Apr 22, 2015 at 04:47 AM · scripting beginner

Swapping Scripts Based off of certain Conditions

I am new to scripting and am working on a game that takes place on a space station where the gravity direction changes on occasion. I know that the way i am trying to handle it isnt the best or most effective way to do it but i still want to try to get it to work.

My Idea is thus,

I have six different scripts that will act as character controllers on a rigidbody Player. I also have a control script that checks the current Gravity Direction based off of triggerevents and swaps the character controller script with the one that matches my manual gravity direction.

The Controller script is attached to the player from the get go.

I am using C#.

How do I add and remove the scripts on the player obj?

My code is still rough and not a lot is implemented but this is where I am and am unable to find anything that looks like it might be what I need.

Any links to documentation and/or a code template would be much appreciated.

Comment
Add comment · Show 6
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 AlwaysSunny · Apr 22, 2015 at 04:44 AM 0
Share

If you plan on changing gravity, ALL of your code which considers orientation $$anonymous$$UST consider this change. That means your character controllers, mouse looks, absolutely everything that cares about "which way is up" needs to consider the project's gravity. The easiest way would involve letting any script who needs this information get it from Physics.gravity. Then "up" would be the inverse, or, -Physics.gravity.

If you want different objects to react to different gravities, that is a more difficult task. You will not be able to use Physics.gravity at all; ins$$anonymous$$d each object will respond to whatever gravity vector (and corresponding "up" vector) you choose, in whatever way you decide to choose.

This is not a simple task. It's certainly not impossible, and it sounds pretty interesting, but ALL of your code needs to respect the fact that their orientation can change.

avatar image AlwaysSunny · Apr 22, 2015 at 04:46 AM 0
Share

Also, this implies not using "six different scripts" - which is a really bad idea anyway. Do you really want to change six different scripts each time you do anything? Bad bad bad. Again: Very very bad idea. ;)

If you absolutely insist, and to actually answer the question, "changing out" scripts is as simple as using RemoveComponent() and AddComponent().

avatar image Sareh Shadowborne · Apr 22, 2015 at 04:51 AM 0
Share

$$anonymous$$y six controller scripts that are being swapped out each take a specific gravity axis into consideration and convert all controls over to that gravity axis. I am doing all of the calculations manually and coding the controllers with the correctly calculated vectors.

avatar image AlwaysSunny · Apr 22, 2015 at 05:42 AM 0
Share

Even so, six scripts is not the best approach. Just replace any code that requires hard Cartesian axes to work relative to the current gravity using Cross Product in conjunction with Physics.gravity. Otherwise you'll wind up with six scripts for every object which considers orientation.

I feel like I may have accidentally derailed your question. Can you comment on what additional information you require?

avatar image Sareh Shadowborne · Apr 22, 2015 at 06:11 AM 0
Share

$$anonymous$$y issue is that while adding the component for some reason I can not delete the olde one.

avatar image AlwaysSunny · Apr 22, 2015 at 06:39 AM 1
Share

Earlier I said you need to use RemoveComponent() but I was mistaken. There is no such thing after all. (I can't remember the last time I wanted to remove a component.) The correct method is Destroy().

You must use an if-statement to check for the presence of each script variant, and remove it if found:

 VariantA variantA = GetComponent<VariantA>();
 if (variantA != null) Destroy( variantA );
 
 VariantB variantB = GetComponent<VariantB>();
 if (variantB != null) Destroy( variantB );
 
 // etc...

It would be best to put these checks in a method that attempts to remove every variant, call that method any time you're ready to change components, then add the variant you DO want with AddComponent() afterwards.

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Sareh Shadowborne · Apr 22, 2015 at 04:27 PM

Thanks To AlwaysSunny for help with pushing me towards the answer

 void ControlSchemeToggle()
     {
         while (GravityForceDirectionToggle.currentGravityDirection == GravityForceDirectionToggle.gravityToggleDictionary["normaly"])
         {
             if (currentControlScheme == GetComponent<NormalGravityDownNegativeYControls>())
             {
                 return;
             }
 
             else
             {
                 GameObject.Destroy (currentControlScheme);
                 currentControlScheme = gameObject.AddComponent<NormalGravityDownNegativeYControls>();
             }
         }
 
         while (GravityForceDirectionToggle.currentGravityDirection == GravityForceDirectionToggle.gravityToggleDictionary["positivey"])
         {
             if (currentControlScheme == GetComponent<GravityUpPositiveYControls>())
             {
                 return;
             }
             
             else
             {
                 GameObject.Destroy (currentControlScheme);
                 currentControlScheme = gameObject.AddComponent<GravityUpPositiveYControls>();
             }
         }
 
     }

This is currently working and swapping out my different control scripts. Thanks a bunch. I originally used if() in place of while() but it wouldnt go to the next check. I am using this six times to change the control scheme to the gravity orientation based on another script that watches for gravity trigger events.

Comment
Add comment · 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

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

3 People are following this question.

avatar image avatar image avatar image

Related Questions

Endless runner spawning infinite tiles 0 Answers

Creating one class or using polymorphism? 1 Answer

How do I make the enemy script/AI stop following me when It is in view of the player camera? 1 Answer

Procedural Mesh : draw labels with triangles and uvs to display a image at specific vertices 0 Answers

Pathfinding in 2d RPG 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