Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • 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
1
Question by Bubadapubada · Feb 25, 2018 at 01:59 PM · scripting problemorbitmultiple objects

Independently using the same script on multiple game objects?

I feel like this question should already be answered but I've scoured the internet and I can't figure out anything that helps.

I've making a space game and I've written a script which draws the ellipse of the orbit of an object, based on its own velocity and position. If I apply this script to one object, it works great! But if I have it on two objects at the same time, the orbits get all messed up. It seems like all the variables are being shared between the same script for different game objects? I saw somewhere on the forums to make all my variables public, but that didn't help either... Any help would be greatly appreciated!!

Here's the script:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class OrbitDrawer : MonoBehaviour
 {
     public GameObject thing;
     public Rigidbody2D rb;
 
     public GameObject attractor;
 
     public Vector3 targetDir;
     public float direction;
     public float force;
 
     public float gravConst = 0.004F;
     public float distance;
 
 
     public float sgp;
     public static Vector3 angMom;
     public float angMomMag;
     public float redMass;
     public Vector3 specRelAngMom;
     public float specRelAngMomMag;
     public Vector3 newSpecRelAngMom;
     public static float orbEnergy;
     public static float sma;
     public static float eccent;
     public float alpha;
     public static float periapsis;
     public static float apoapsis;
     public Vector2 ecVec;
     public Vector3 angVel;
     public float angVelMag;
     public float momOfInertia;
     public float flightPathAngle;
 
 
     public static float sMina;
     public float centerHeight;
     public Vector3 Center;
 
     public static Vector3 Forceforce;
 
     public Vector3 actualAttractorToPlayer = Vector3.zero;
     public Vector3 previousAttractorToPlayer = Vector3.zero;
     public float angleDifference;
     public float orbitalAngle;
 
 
     public float a = 2;
     public float b = 1;
     public float h = 0;
     public float k = 0;
     public float theta = 0;
     public int resolution = 1000;
 
     public Vector3[] positions;
 
     public float orbitWidth;
 
     public static float height;
 
     void Start()
     {
         rb = GetComponent<Rigidbody2D>();
     }
 
     void Update()
     {
 
         a = sma;
         b = sMina;
         theta = orbitalAngle;
         centerHeight = apoapsis - sma;
         h = centerHeight * Mathf.Cos(theta * Mathf.Deg2Rad);
         k = centerHeight * Mathf.Sin(theta * Mathf.Deg2Rad);
 
         positions = CreateEllipse(a, b, h, k, theta, resolution);
         LineRenderer lr = GetComponent<LineRenderer>();
         lr.positionCount = resolution + 1;
         for (int i = 0; i <= resolution; i++)
         {
             lr.SetPosition(i, positions[i]);
         }
 
         lr.startWidth = Camera.main.orthographicSize * orbitWidth;
         lr.endWidth = Camera.main.orthographicSize * orbitWidth;
     }
 
     void FixedUpdate()
     {
         //All the maths!!
 
         targetDir = attractor.transform.position - thing.transform.position;
 
         distance = Vector2.Distance(thing.transform.position, attractor.transform.position);
 
         force = ((Planet.mass * rb.mass * gravConst) / (distance * distance));
 
         Vector2 dir = targetDir.normalized;
         rb.AddForce(dir * force, ForceMode2D.Force);
 
 
         sgp = gravConst * (Planet.mass + rb.mass);
 
         //Calculate Specific Relative Angular Momentum(Cross of the position and the velocity vectors)
 
         specRelAngMom = Vector3.Cross(thing.transform.position, rb.velocity);
         specRelAngMomMag = specRelAngMom.magnitude;
 
         //Calculate orbital energy
         orbEnergy = ((rb.velocity.magnitude * rb.velocity.magnitude) / 2) - (sgp / distance);
 
         //Calculate semi-major axis and semi-minor axis
         sma = -(sgp / (2 * orbEnergy));
         sMina = sma * (Mathf.Sqrt(1 - (eccent * eccent)));
 
 
         //Calculate Eccentricity Vector(vector from the apopapsis to the periapsis)
         ecVec = ((Vector3.Cross(rb.velocity, specRelAngMom)) / sgp) - (thing.transform.position / thing.transform.position.magnitude);
 
         //Make the orbital angle negative when it should be
         if (Vector3.Cross(new Vector3(1, 0, 1), (ecVec * -1)).x < 0)
         {
             orbitalAngle = Vector3.Angle(new Vector3(1, 0, 0), (ecVec * -1));
         }
         else
         {
             orbitalAngle = -Vector3.Angle(new Vector3(1, 0, 0), (ecVec * -1));
         }
 
         //Calculate Eccentricity
         eccent = Mathf.Sqrt(1 + ((2 * (orbEnergy) * specRelAngMomMag * specRelAngMomMag) / (sgp * sgp)));
 
         //Calculate periapsis and apoapsis
         periapsis = ((1 - eccent) * sma);
         apoapsis = ((1 + eccent) * sma);
     }
 
     //Function for creating an ellipse. a is sma, b is sMina, (k, h) is the center, theta is the angle, and resolution is the number of points on the ellipse
     Vector3[] CreateEllipse(float a, float b, float h, float k, float theta, int resolution)
     {
 
         positions = new Vector3[resolution + 1];
         Quaternion q = Quaternion.AngleAxis(theta, Vector3.forward);
         Vector3 center = new Vector3(h, k, -0.0f);
 
         for (int i = 0; i <= resolution; i++)
         {
             float angle = (float)i / (float)resolution * 2.0f * Mathf.PI;
             positions[i] = new Vector3(a * Mathf.Cos(angle), b * Mathf.Sin(angle), -0.0f);
             positions[i] = q * positions[i] + center;
         }
 
         return positions;
     }
 }

Comment
Add comment · Show 3
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 pako · Feb 25, 2018 at 02:01 PM 0
Share

You are using many static variables and that's what's causing the problem.

Static variable values are shared between all instances of the object.

So, just remove the static keyword from all variable declarations, whose values you want to be unique for each instance.

avatar image Bubadapubada pako · Feb 25, 2018 at 02:15 PM 0
Share

Thank you!! I knew there was something I just wasn't getting.

avatar image pako Bubadapubada · Feb 25, 2018 at 02:19 PM 0
Share

You are welcome!

Please don't forget to mark my reply as the accepted answer (Click the check-mark icon to make it green)

2 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by Lilius · Feb 25, 2018 at 02:06 PM

Make your variables private instead. And don't use static variables, they most likely cause things to get messed up when using same script on many objects.

Comment
Add comment · Show 2 · 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 Flow-Hockey · Sep 12, 2019 at 04:35 PM 0
Share

I have a very similar problem, but I need to access the variables in my script from another script - so I'm assu$$anonymous$$g I need to have public variables.

Should I be making function calls ins$$anonymous$$d?

avatar image Lilius Flow-Hockey · Sep 12, 2019 at 04:57 PM 0
Share

You should not use static variables just to have an easy access to variable. Getting reference to object and accessing its public (non static) variables is better, but using properties is even better: https://docs.microsoft.com/en-us/dotnet/csharp/program$$anonymous$$g-guide/classes-and-structs/properties

avatar image
0

Answer by DrawMen1999 · Sep 12, 2019 at 04:49 PM

Static variables are shared by every instance of the script, so remove the static and it should work.

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.

Follow this Question

Answers Answers and Comments

137 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to create a changing orbit from elliptical to planar and back? 0 Answers

Script stops working when on multiple objects 2 Answers

non-static Variable in script on multiple gameObjects reset. Why? 1 Answer

I want to move two bar simultaneously.How can I do?,I want to move multiple object with using tags,so How can I do ? 0 Answers

Multi-gun Aiming System 1 Answer


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