Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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
0
Question by Mythrell · Aug 19, 2014 at 06:30 PM · c#transform

Creating Solar System from script with FX Planet Orbit

I'm new to unity and C#, so I've been trying to do a simple project and create a Solar System from script with the FX Planet Orbit script and specially with it's C# version.

Making the planets gameObjects by hand in unity it works normally, but now that I'm trying to create the gameObject ( Mars ) from a script I've ran into a problem which I can't figure out. I suspect it's something simple and related to transforms in code below.

Mars is supposed to orbit Sun (obj_sun) by all the values I've set in CreatePlanet.cs, basicly trying to give all required variables which you give when making the gameObject from the Editor side.

I've spent more time with this than is healthy but I simply cannot seem to be able to do this. Any tips are appreciated as well, as you can see I'm just trying to make it work with simple logics here :)

 CreatePlanet.cs:
 line 17:    mars.GetComponent<TV_Orbit>().Parent = GameObject.Find("obj_sun").transform;
 
 TV_Orbit.cs
 line 85:    OrbitCenter.position = Parent.position;

I get following error when trying to run the script:

 NullReferenceException: Object reference not set to an instance of an object
 TV_Orbit.Awake () (at Assets/Scripts/TV_Orbit.cs:85)
 UnityEngine.GameObject:AddComponent(String)
 CreatePlanet:Start() (at Assets/Scripts/CreatePlanet.cs:17)

My own script CreatePlanet.cs:

 using UnityEngine;
 using System.Collections;
 
 public class CreatePlanet : MonoBehaviour {

 // Use this for initialization
 void Start () {

     Debug.Log("I am alive!");

     GameObject mars = GameObject.CreatePrimitive(PrimitiveType.Sphere);
     //mars.transform.position = new Vector3(20f, 0, 0);
     mars.name = "obj_mars";
     mars.transform.localScale = new Vector3(1000, 1000, 1000);
     mars.renderer.material.color = Color.red;
     mars.transform.parent = GameObject.Find("obj_sun").transform;
     mars.AddComponent("TV_Orbit");
     mars.GetComponent<TV_Orbit>().OrbitalDistance = 2279.20f;
     mars.GetComponent<TV_Orbit>().Parent = GameObject.Find("obj_sun").transform;
     mars.GetComponent<TV_Orbit>().Parent.position = GameObject.Find("obj_sun").transform.position;
     Debug.Log(GameObject.Find("obj_sun").transform.position);
     mars.GetComponent<TV_Orbit>().TidalLock = false;
     mars.GetComponent<TV_Orbit>().LockOrbit = false;
     mars.GetComponent<TV_Orbit>().OrbitAngle = 1;
     mars.GetComponent<TV_Orbit>().KeepTime = false;
     mars.GetComponent<TV_Orbit>().OrbitOffset = new Vector3(0,0,0);
     mars.GetComponent<TV_Orbit>().OrbitPosOffset = 0;
     mars.GetComponent<TV_Orbit>().OrbitalPeriod = 1;
     mars.GetComponent<TV_Orbit>().Name = "Mars";
     mars.GetComponent<TV_Orbit>().RotationPeriod  = 1.01f;
     mars.GetComponent<TV_Orbit>().RotInOrbit = 686;
     mars.GetComponent<TV_Orbit>()._DrawOrbit = true;
     mars.GetComponent<TV_Orbit>().AxialTilt = 25.19f;
     mars.GetComponent<TV_Orbit>().enabled = true;
 }
 
 // Update is called once per frame
 void Update () {
 
 }

}

FX Planet Orbit TV_Orbit.cs which I've attached to the gameObjects:

 using UnityEngine;
 using System.Collections;
 
 public class TV_Orbit : MonoBehaviour {
 
     public int TimeMultiplier = 200000;
     public string Name = "";
     public Transform Parent;
 
     public enum Orbit {Auto, Manual}
     public Orbit SetOrbit;
 
     public enum Rotation {Auto, Manual}
     public Rotation SetRotation;
     
     public enum Season {Auto, Manual}
     public Season SetSeason;
     
     public bool TidalLock;
     public bool LockOrbit;
     public float OrbitAngle;
     public bool KeepTime;
     private Transform ThisTransform;
     private float EarthDays = 365.242199f;
     
     // Orbit Stats
     public float OrbitalPeriod = 1.0f; // Earth Years
     public float OrbitalDistance = 2f;
     public Vector3 OrbitOffset;
     public float OrbitPosOffset;
     public float OrbitStartPos;
     public int OrbitYears;
     public int OrbitDays;
     public int OrbitHours;
     public int OrbitMinutes;
     public float OrbitSeconds;
     private float OrbitalTime;
     private float OrbitalDegSec;
     
     //Rotation Stats
     public float RotationOffset;
     public float RotationPeriod; // Earth Hours
     public int RotationYears;
     public int RotationDays;
     public int RotationHours;
     public int RotationMinutes;
     public float RotationSeconds;
     private float RotationDegSec;
     private float RotationTime;
     
     // Planetary Stats
     public float AxialTilt;
     public int HoursInDay;
     public int RotInOrbit;
     //Planet Counters
     public int CounterYear;
     public int CounterDay;
     public int CounterHour;
     public int CounterMinute;
     public float CounterSecond;
     public float CurrentOrbitPos;
     public bool OrbitOffSetYear;
     private float RotCounter;
     private float OrbCounter;
     
     //Draw Orbit
     public bool _DrawOrbit = false;
     public float DisplaySize = 0.05f;
     public Color DisplayColor = Color.blue;
     public int Segments = 100;
     public Texture2D DisplayTexture;
     public int DisplayTiling = 50;
     public bool UseTexture;
     private Transform ThisOrbit;
     private LineRenderer LR;
     
     private Transform OrbitCenter;
     
     public void Awake(){
         ThisTransform = transform;
         var ThisLEuler = ThisTransform.localEulerAngles;
         ThisLEuler.z = AxialTilt;
         ThisTransform.localEulerAngles = ThisLEuler;
         OrbitCenter = new GameObject("OrbitCenter").transform;
         OrbitCenter.position = Parent.position;
         ThisTransform.parent = OrbitCenter;
         ThisTransform.localPosition = new Vector3(0,0,OrbitalDistance);
         var OCEuler = OrbitCenter.eulerAngles;
         OCEuler.x = OrbitAngle;
         OrbitCenter.eulerAngles = OCEuler;
         OrbitCenter.Rotate(0,OrbitPosOffset,0);
         
         
         if(_DrawOrbit){
             if(GameObject.Find("Orbits") == null){
                 GameObject Orbits = new GameObject("Orbits");
                 Orbits.transform.position = Vector3.zero;
                 Orbits.transform.eulerAngles = Vector3.zero;
             }
         }
     }
     
     public void Start(){
         SetupPlanet();
         
         if(OrbitOffSetYear){
             OrbCounter = OrbitPosOffset;
         }
         if(LockOrbit){
             KeepTime = false;
         }
         if(_DrawOrbit){
             SetupDrawOrbit();
         }
     }
     
     public void SetupDrawOrbit(){
         GameObject Orbit = new GameObject("Orbit_Path");
         GameObject Obits = GameObject.Find("Orbits");
         var OrbEA = Orbit.transform.eulerAngles;
         OrbEA.x = OrbitAngle;
         Orbit.transform.eulerAngles = OrbEA;
         Orbit.transform.parent = Obits.transform;
         Orbit.transform.position = Parent.position;
         Orbit.AddComponent<LineRenderer>();
         LR = Orbit.GetComponent<LineRenderer>();
         LR.SetWidth(DisplaySize,DisplaySize);
         LR.material.shader = Shader.Find("Particles/Additive");
         LR.material.SetColor ("_TintColor", DisplayColor);
         LR.useWorldSpace = false;
         LR.SetVertexCount (Segments + 1);
         
         if(DisplayTexture != null){
             var mTScale = LR.material.mainTextureScale;
             LR.material.mainTexture = DisplayTexture;
             mTScale.x = DisplayTiling;
             LR.material.mainTextureScale = mTScale;
         }
         
         ThisOrbit = Orbit.transform;
         
         float Angle = new float();
         for (int i = 0; i < (Segments + 1); i++){
             Vector2 NewRadius = new Vector2(Mathf.Sin (    Mathf.Deg2Rad * Angle) * OrbitalDistance, 
                                             Mathf.Cos (Mathf.Deg2Rad * Angle) * OrbitalDistance);
             
             LR.SetPosition (i,new Vector3(NewRadius.y,0,NewRadius.x));
             Angle += (float)(360.0 / Segments);
         }
     }
     
     public void SetupPlanet(){
         //Setup Orbit Time
         if(SetOrbit == 0){
             OrbitalTime = ((((EarthDays * OrbitalPeriod) * 24) * 60) * 60);
             OrbitalDegSec = (360 / OrbitalTime) * TimeMultiplier;
         }else{
             OrbitalPeriod = 0;
             OrbitalTime = ((((((((OrbitYears * EarthDays) + OrbitDays) * 24) + OrbitHours) * 60) + OrbitMinutes) * 60) + OrbitSeconds);
             OrbitalDegSec = (360 / OrbitalTime) * TimeMultiplier;
         }
         
         //Setup Rotation Time
         if(!TidalLock){
             if(SetRotation == 0){
                 RotationTime = (((24 * RotationPeriod) * 60) * 60);
                 RotationDegSec = (360 / OrbitalTime) * TimeMultiplier;
             }else{
                 RotationPeriod = 0;
                 RotationTime = ((((((((RotationYears * EarthDays) + RotationDays) * 24) + RotationHours) * 60) + RotationMinutes) * 60) + RotationSeconds);
             }
             RotationDegSec = (360 / RotationTime) * TimeMultiplier;
             RotInOrbit = Mathf.RoundToInt(OrbitalTime / RotationTime);
             HoursInDay = Mathf.RoundToInt((RotationTime / 60) / 60);
         }
     }
     
     public void Update(){
         float ODS = OrbitalDegSec * Time.deltaTime;
         if(!LockOrbit){
             OrbitStartPos += ODS;
             OrbitCenter.Rotate(0,ODS,0);
         }
         
         // Update Rotation
         if(TidalLock){
             ThisTransform.LookAt(Parent);
             if(KeepTime){
                 UpdateCounters(0f, ODS);
             }
         }else{
             float RotDegSec = RotationDegSec * Time.deltaTime;
             if(KeepTime){
                 UpdateCounters(RotDegSec, ODS);
             }
             ThisTransform.Rotate(0,RotDegSec, 0, Space.Self);
         }
     }
     
     public void UpdateCounters(float RotDegSec ,float ODS ){
         
         //Count Orbits / Years
         if((OrbCounter + ODS) >= 360){
             CounterYear += 1;
             CounterDay = 0;
             OrbCounter = (OrbCounter + ODS) - 360;
         }else{
             OrbCounter += ODS;
         }
         
         CurrentOrbitPos = OrbCounter;
         
         //Count Days    
         if((RotCounter + RotDegSec)>= 360){
             CounterDay += 1;
             RotCounter = (RotCounter + RotDegSec) - 360;
         }else{
             RotCounter += RotDegSec;
         }
         
         var CurrentTime = (RotCounter / 360) * RotationTime;
         
         //Count Hours
         CounterHour = (int)(CurrentTime / 60) / 60;
         
         //Count Minutes    
         if(CounterHour > 0){
             CounterMinute = (int)(CurrentTime / 60) - (CounterHour * 60);
         }else{
             CounterMinute = (int)(CurrentTime / 60);
         }
         
         //Count Seconds
         if(CounterHour > 0 && CounterMinute > 0){
             CounterSecond = CurrentTime - ((CounterMinute + (CounterHour * 60)) * 60);
         }else if(CounterHour > 0 && CounterMinute == 0){
             CounterSecond = CurrentTime - ((CounterHour * 60) * 60);
         }else if(CounterHour == 0 && CounterMinute > 0){
             CounterSecond = CurrentTime - (CounterMinute * 60);
         }else if(CounterHour == 0 && CounterMinute == 0){
             CounterSecond = CurrentTime;
         }
     }
     
     void LateUpdate(){
         Vector3 CurPos = Parent.position + new Vector3(OrbitOffset.x, OrbitOffset.y,OrbitOffset.z);
         OrbitCenter.position = CurPos;
         if(_DrawOrbit){
             ThisOrbit.position = CurPos;
         }
     }
 }

Comment
Add comment · Show 4
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 tanoshimi · Aug 19, 2014 at 06:38 PM 0
Share

I can't see anywhere where you're defining Parent...

avatar image robertbu · Aug 19, 2014 at 10:04 PM 0
Share

Parent is a public Transform. Typically these get defined by dragging dropping a game object on the parent variable, so it looks like the code is expecting you to drag and drop the parent game object from the hierarchy on to the 'Parent' variable in this component.

avatar image Kiwasi · Aug 19, 2014 at 10:50 PM 0
Share

For efficiency don't use GetComponent more then you have to.

 TV_Orbit tv_Orbit = mars.AddComponent<TV_Orbit>();
 tv_orbit.OrbitalDistance = 2279.20f;
 ....
avatar image Mythrell · Aug 20, 2014 at 03:50 AM 0
Share

robertbu: Yes, original use of the script requires you to drag and drop the parent game object (or to be more accurate, the object you want your other object to orbit) to it. In this case, it would be obj_sun.

Editor code:

myTarget.Parent = (Transform)EditorGUILayout.ObjectField ("Parent $$anonymous$$ass: ", myTarget.Parent, typeof(Transform), true);

This is the reason I'm trying to pass it mars.GetComponent().Parent = GameObject.Find("obj_sun").transform;

Bored$$anonymous$$ormon: You're right, that makes sense.

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Mythrell · Aug 21, 2014 at 07:34 AM

Ok I think I got this figured out. Basically I'm setting GameObject parameters after the TV_Orbit.cs has already been ran (on game object creation) so it's a tad too late to try and set them later.

All I needed to do to get the result I wanted was to run the script again, ie.

  mars.GetComponent<TV_Orbit>().Awake();
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

3 People are following this question.

avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

C#:Unity:Having trouble reference Rigidbody2d from different script 2 Answers

How to instanciate transform to element of a list?,How Get Transform of a instanciated Prefap 3 Answers

Getting index of the smallest number in a list 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