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. Dismiss Notice

Question Cannot Update Component Variables Within Script (Unfamiliar Script Structure)

Discussion in 'Scripting' started by FlyingKountach, Jul 11, 2023.

  1. FlyingKountach

    FlyingKountach

    Joined:
    Jun 14, 2023
    Posts:
    17
    Hello,
    I have this script which assigns an .obj file as a GameObject during runtime. The script opens a Windows File Explorer window and I get to select an .obj file. I want to be able to add components to the 3D object and update those components after the GameObject is assigned as the .obj file. Since this is outside of the normal examples that I've seen of applying and updating GameObjects, I'm not sure how to do it properly. There is no Start or Update functions, and this originally is not my code, I'm just trying to modify it. The components are applied fine, but only some updates like "rigidbody.useGravity = false;" work. Any ideas on how to do this? Thanks!

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using System.IO;
    4. using System.Text;
    5. using System.Runtime.InteropServices;
    6. using UnityEngine;
    7. using UnityEngine.UI;
    8. using UnityEngine.Networking;
    9. using SFB;
    10. using TMPro;
    11. using Dummiesman;
    12. using Valve.VR.InteractionSystem;
    13.  
    14. public class OpenFile : MonoBehaviour
    15. {
    16.     public GameObject model;
    17.     public float scale;
    18.  
    19.     public void OnClickOpen()
    20.     {
    21.         string[] paths = StandaloneFileBrowser.OpenFilePanel("Open File", "", "obj", false);
    22.         if (paths.Length > 0)
    23.         {
    24.             StartCoroutine(OutputRoutineOpen(new System.Uri(paths[0]).AbsoluteUri));
    25.     }
    26. }
    27.     private IEnumerator OutputRoutineOpen(string url)
    28.     {
    29.         UnityWebRequest www = UnityWebRequest.Get(url);
    30.         yield return www.SendWebRequest();
    31.         if (www.result != UnityWebRequest.Result.Success)
    32.         {
    33.             Debug.Log("WWW ERROR: " + www.result);
    34.         }
    35.         else
    36.         {
    37.             MemoryStream textStream = new MemoryStream(Encoding.UTF8.GetBytes(www.downloadHandler.text));
    38.             if (model != null)
    39.             {
    40.                 Destroy(model);
    41.             }
    42.             model = new OBJLoader().Load(textStream);
    43.             model.transform.localScale = new Vector3(-scale, scale, scale); //Set position of parent model and reverse X to show properly
    44.             model.transform.position = new Vector3(0, 2f, 0);
    45.  
    46.             model.AddComponent<BoxCollider>();
    47.             model.AddComponent<Rigidbody>();
    48.             model.AddComponent<Interactable>();
    49.             model.AddComponent<Throwable>();
    50.  
    51.             BoxCollider boxCollider = model.GetComponent<BoxCollider>();
    52.             Rigidbody rigidbody = model.GetComponent<Rigidbody>();
    53.             Interactable interactable = model.GetComponent<Interactable>();
    54.  
    55.             boxCollider.center = new Vector3(0.0015f, -0.036f, 0.016f);
    56.             boxCollider.size = new Vector3(0.092f, 0.138f, 0.032f);
    57.  
    58.             rigidbody.useGravity = false;
    59.             rigidbody.drag = 10.0f;
    60.             rigidbody.angularDrag = 10.0f;
    61.  
    62.             interactable.hideControllerOnAttach = true;
    63.             interactable.hideHandOnAttach = true;
    64.             interactable.highlightOnHover = false;
    65.         }
    66.     }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    If this is intended for editor use, just drag the .OBJ file into Unity and let Unity take care of it.

    If this is intended for runtime use, you would need to reimplement Unity within Unity to accomplish what you say.

    If you have a GameObject you can always use .AddComponent<T>() to add Components to it.
     
  3. FlyingKountach

    FlyingKountach

    Joined:
    Jun 14, 2023
    Posts:
    17
    This is intended for runtime use, so I'm not able to access the Unity editor. I'd like to do something like this: https://docs.unity3d.com/ScriptReference/BoxCollider-size.html, but this code that I have is structured differently so I'm not sure how to implement it. As I said, I'm able to add components such as a box collider and a rigidbody to the game object successfully. The problem is I don't know how to change the box collider's size, among other things. The Unity webpage I listed explains how, but the code I'm using is structured differently.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    Generally speaking every field in the inspector can be accessed via code.

    Hurry over to the Scripting Reference page for all the Components you want to interoperate with.
     
  5. FlyingKountach

    FlyingKountach

    Joined:
    Jun 14, 2023
    Posts:
    17
    Sorry let me rephrase that. https://docs.unity3d.com/ScriptReference/BoxCollider-size.html this page tells me exactly how to update the box collider size, but the code I'm using doesn't have a Start or Update function. Since the code I'm using is not structured like the code in the webpage, how can I adjust my code to get boxCollider.size to update successfully? My code tells it exactly how to update, but it will not.
     
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    That just sounds like you wrote a bug, and that can only mean...

    Time to start debugging! Here is how you can begin your exciting new debugging adventures:

    You must find a way to get the information you need in order to reason about what the problem is.

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling
    Debug.Log()
    statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the names of the GameObjects or Components involved?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    "When in doubt, print it out!(tm)" - Kurt Dekker (and many others)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.
     
  7. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,769
    Because maybe nothing is calling/running the code??? You need to actually write some code that will call these functions, such as through inputs or UI.