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

To assign a Vector3 to System.Object

Discussion in 'Editor & General Support' started by tribaleur, Sep 20, 2018.

  1. tribaleur

    tribaleur

    Joined:
    Jan 19, 2017
    Posts:
    34
    Hello,

    I'm tryin to assign a Vector3 object into a System.Object variable. But if i don't create a Vector3 variable it doesn't work and i don't understand why.

    here is my code :
    Code (CSharp):
    1. System.Object result;
    2.  
    3. // ...
    4.  
    5. result = Vector3.zero;
    6.  
    7. Ray ray = this._camera.ScreenPointToRay(Input.mousePosition);
    8. RaycastHit hit;
    9.  
    10. if (Physics.Raycast(ray, out hit, (this._camera.transform.position.y + 10f))){
    11.     result = new Vector3(hit.point.x, 0, hit.point.z);    // result = (0, 0, 0) => NON OK
    12.  
    13.     Vector3 test = new Vector3(hit.point.x, 0, hit.point.
    14.     result = test;                                                         // result = (x, 0, z) => OK
    15. }
    Do you have an idea why the first assignation doesn't work and the second do ?

    Thanks
     
  2. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    Sorry, this might not be a satisfying answer.

    You can assign most objects to System.Object because most objects inherit from another class that inherits from a C# System.Object. Vector3 is a struct created by Unity (not built into C#) and does not inherit from anything, so Vector3 data can only be stored in a Vector3 unless it's converted.

    Basic types like "int" and "float" use some black-box magic behind the scenes to allow them to be stored in a System.Object. The best way to sum it up is that they get converted to a System.Object automatically.

    If you want more info on any of this, the first answer to this question has a lot of great info: https://stackoverflow.com/questions...-object-referencetype-and-still-be-valuetypes
     
  3. tribaleur

    tribaleur

    Joined:
    Jan 19, 2017
    Posts:
    34
    Hello,

    Your answer is perfect.
    I didn't noticed that an Unity Object was not necessary a System.Object's child.

    Thanks !