#archived-code-advanced

1 messages ¡ Page 195 of 1

real talon
#

He's just showing what we discussed 2 hours ago

#

I would not have seen it in works in progress, i never visit that one

alpine adder
#

Hello! I have question!

#

I currently have a pinch scale touch control. where when I zoom out the object gets bigger! how can I inverse that

#

To where I zoom out object gets smaller

cunning kite
#

Does anybody have some good reading or videos on behavior tree implementations in Unity?

#

Trying to find something that isn't a 20 minute video explaining just the basics

real talon
# alpine adder

Posting the code instead of a screenshot of the code is easier to work with.
But I guess transformToScale.localScale = initialScale * (1 - touchDistanceDifference);

alpine adder
#

DIdn't want to flood it

real talon
#

What piece of code am I looking at now?

alpine adder
#

ah shit

#

sorry

real talon
#

This seems like rotational code

alpine adder
#
    protected override void scaleStart()
     {
         scaleCoroutine = StartCoroutine(scaleDetection());
     }

     protected override void scaleEnd()
     {
         StopCoroutine(scaleCoroutine);
     }

     private IEnumerator scaleDetection()
     {
         Vector2 currentTouchPrimary = touchControls.Touch.PrimaryFingerPosition.ReadValue<Vector2>();
         Vector2 currentTouchSecondary = touchControls.Touch.SecondaryFingerPosition.ReadValue<Vector2>();

         float initialDistance = Vector2.Distance(currentTouchPrimary, currentTouchSecondary);
         Vector3 initialScale = transformToScale.localScale;
         curState = State.SCALETRANSLATE;
         while (true)
         {
             if (curState == State.SCALETRANSLATE)
             {
                 currentTouchPrimary = touchControls.Touch.PrimaryFingerPosition.ReadValue<Vector2>();
                 currentTouchSecondary = touchControls.Touch.SecondaryFingerPosition.ReadValue<Vector2>();

                 float currentDistance = Vector2.Distance(currentTouchPrimary, currentTouchSecondary);


                 //if accidentally touched or pinch movement is very very small
                 if (Mathf.Approximately(initialDistance, 0))
                 {
                     yield return null;
                 }

                 var touchDistanceDifference = (currentDistance / initialDistance);


                 transformToScale.localScale = initialScale * ( 1- touchDistanceDifference);
             }
             
             yield return null;
         }
     }
    
real talon
#

Yeah does that work?

gray pulsar
alpine adder
#

ooohhh going to try that out

#

1 second yall

alpine adder
alpine adder
# real talon Yeah does that work?

The -1 worked as well it was just a little harsher and on initial press would reset the values but with some finagling it would work im sure

real talon
#

Tachyons way is nicer

#

Anyhow, glad it worked

alpine adder
#

my goodness. that was just 3 hours of struggle when I should've gone here first

#

Thank you all!!

gray pulsar
#

np

novel wing
#

I have a script with a lot of fields for configuration, I am planning on moving these fields in to a struct instead. How can I make sure that values that are already set on prefabs are properly copied in to the new struct?

untold moth
narrow girder
#

Question regarding streaming asset bundles (addressables might be relevant too?)
I'm trying to load an existing, published catalog into the editor, create a new asset with a reference to a scriptable object inside that catalog, and save it as a new addressable streaming bundle
Is that possible? I can load something from an existing catalog, and instantiate it, but trying to copy a reference just clears itself, because it's an invalid reference...

undone coral
#

why into the editor?

#

from your game?

#

or a different game you dont' have the project for?

#

you can't mod this way

undone coral
#

the best way to "make sure" is to use source control and compare

undone coral
#

i guess it's fine this way

#

you can use += performed instead and it will be simpler and clearer

narrow girder
# undone coral what is your objective?

modding, yea. I can load the game assets into the editor, and my own assets back into the game at runtime.. but no way to reference game assets from my assets

buoyant vine
#

why dont you make modding based on xml or json

narrow girder
#

in this case, I'm trying to mod a released game that the devs are happy for people to mod, but aren't will to build tools

novel wing
regal olive
#

i need a way to disable the convex collider triangle limit

signal osprey
#

hey, i'm running into a little issue here. i can't get contact points for within the collider if it's a trigger. i tried looking up some solutions and found one that says giving the sphere a rigidbody and setting isKinematic to true should work, but it still collides with the ball. any idea what to do?

signal osprey
#
void Start()
    {
        m_Collider = GetComponent<Collider>();
        m_Center = m_Collider.bounds.center;
    }
 void OnCollisionEnter(Collision collision)
    {
        ContactPoint contact = collision.contacts[0];
        strength = m_Center - contact.point;
        Debug.Log(strength);
        Debug.Log(strength.magnitude);
    }

If my collider is a sphere, strength.magnitude should always be the same, right? the distance from the surface of the sphere to the centre is what it's meant to be modelling, so it shouldn't change. yet, it does. what have i done wrong here?

real talon
signal osprey
#

the collider is currently not a trigger, because i couldn't get contact points to work with it as a trigger

real talon
#

Hmm

#

Well can't help atm, i'm at a party, but that would make it quite hard without a trigger. If it's too far in the sphere it would resolve the collision with extreme force right? The ball would bounce off really hard that way.

signal osprey
#

you're correct haha, that does tend to occur

real talon
#

I do not understand why OnTriggerEnter would not work, because that also has a OnTriggerEnter(Collision collision)

#

The collision should also have contact points

signal osprey
#

if i change it to that, i get this error message

#

and if i change the first collision to collider, i get this

real talon
#

Ohh damn, I read that wrong then.

signal osprey
#

thanks for trying to help though, enjoy your party 👍

real talon
severe grove
#

Is there a way to pass a class as a variable? I.e. var foo = CustomClass; bar = new foo();

#

I have a class that I need to run new () on but only at a specific time. If I just do var foo = new CustomClass(); it runs on declaration.

urban warren
#

If so then you want to use a struct instead most likely. The other option is to implement a Copy() method which creates a new instance of the class and manually set the fields of the copy to be the same as the original.

severe grove
#

I'm running into a stack overflow error.

severe grove
#

I have an abstract class Dialog. I extend this Dialog into Foo, Bar, ect. Each of these has a function that will load a specific Dialog when run. If I just do var x = new Bar() it runs new Bar() on declaration. Which contains a reference to new Foo() which then runs.....

#

I need a way to make Foo and Bar a variable that I can run new() on.

urban warren
#

It also kind of sounds like you might not really understand how C# works and are trying to do things in a sort of backwards way.

severe grove
#

This is causing a stack overflow error when I run because it loads dialog NewGame2 which has a reference to NewGame1. I need to run new NewGame2() at a specific time so I want to use it as a variable. responses = new List<RefDialogResponse>() { new RefDialogResponse() { label= "Next", tooltip = "", checks = new List<RefDialogCheck>(), failedCheckTooltip = "", Effects = new List<RefDialogEffect>() { new RefDialogEffect() { contextType = ContextType.Dialog, connectedDialog = new NewGame2(), context = new LoadDialog(), } } }, };

#

both of those new Class statements need to go away.

urban warren
#

Can you show the relevant bits of the constructors too?

severe grove
#

NewGame2 is the same datastructure as this line because they both extend an abstract class.

urban warren
severe grove
#

these are classes that store data. public abstract class RDialog { public abstract Guid ID { get; set; } public abstract string content { get; set; } public abstract string dialogHeader { get; set; } public abstract Texture dialogImage { get; set; } public abstract string imageArtist { get; set; } public abstract List<RefDialogResponse> responses { get; set; } }

#

I need to figure out how to reference them without calling new to be honest.

#

I'll have a think about it. Thanks for responding.

undone coral
#

What is your objective?

#

Gameplay wise?

severe grove
#

When the player hits a button it creates a new instance of that specific dialog which gets stored into a static variable. I then have an event that loads the new dialog with a bunch of classes accessing that stored instance.

undone coral
undone coral
#

Like it’s gathering data so that you can load a scene with that data later?

#

Like a choose your level dialog

#

Or whatever

#

What is the dialog

severe grove
#

sort of. Instead of doing scriptable objects I am using classes. I want to write it all in code.

#

these Dialogs are acting like a scriptable object. They contain data and are extending an abstract class.

undone coral
#

What is the gameplay exactly

#

For the dialog and maybe one sentence on what the game is

severe grove
#

Game loads dialog. Dialog has a bunch of responses. responses populate buttons. player chooses buttons. event chooses response from list by index. runs that response, in this case, loads another dialog class.

#

Game is text based turn by turn.

undone coral
#

I see

undone coral
#

Are you trying to say a prompt?

#

A lot of people struggle with “how do I wait for input”

#

You probably want something like yield return new WaitForAnswerToDialog()

#

Would that be helpful?

severe grove
#

maybe. I'll look it over.

undone coral
#

It doesn’t exist

#

I’m trying to say that conceptually you are building this big cathedral

#

To basically wait for the user to make a choice or something

#

It would be really intuitive to wait in a function but you can’t

#

At least not yet

#

I don’t know why you have more than one dialog class or why it’s called dialog

#

You should just have one class for the UI that is asking what the user wants to do, which sounds like dialog

#

Unless you meant to write dialogue

severe grove
#

I have been handling it by storing all static data in a data class. When the player does something, it triggers an event which acts on that data in the static class.

#

I.E. I click a button. It opens Data.dialog.responses[i]

undone coral
#

So you meant dialogue as in narrative text with choosable story threads?

severe grove
#

yes.

undone coral
#

Not dialog as in the programming term for popup windows

#

That ask single questions

#

Like the save file dialog

#

Lol

severe grove
#

Dialog in the narrative sense. It is the naming convention I chose to reference any data that populated the big window.

undone coral
#

Okay well have you looked at Ink

#

The word for that is dialogue

#

You gotta use the right names for things

severe grove
#

duly noted.

undone coral
#

You should use Ink

#

If you want a UI around ink there’s Dialogue Manager asset store asset

#

And you can customize it to pretty much whatever

#

Have you ever tried Ink?

#

Maybe you didn’t find it because you wrote “dialog” into the asset store

#

Jk

#

The game looks cool

#

I really like Ink and use it for any narrative content

#

Because writers can handle it easily

#

It already looks like a screenplay which is really reassuring

severe grove
#

Awesome. Thank you very much.

#

I have not tried it before but sounds like it would be worth a look.

undone coral
#

I like the single keyboard press energy

#

You should try formatting it for portrait for phones too

#

Although it’s tough to say if the average phone user reads lol

#

Some read

#

What’s great about ink is you could publish an ePub and people can just play your game

#

Like in their kindle

#

Or from a text message

#

At least chapter 1

#

You’ll see it works well with stuff like inventory

real talon
signal osprey
severe grove
signal osprey
#

so far i've managed to make it so the ball just bounces off in the direction of the normal, but i have two issues

  1. the aforementioned trigger issue
  2. the calculation i'm using for the ball vector is
    rb.velocity = pos * (5 / strength.magnitude) * 7 + Vector3.up * 10
#

the issue with that, is if i have an if statement beforehand, it only uses the "Vector3.up * 10" part.

if (control.hit == true)
            rb.velocity = pos * (5 / strength.magnitude) * 7;

(with control.hit checking if the player has pressed the hit button)

real talon
#

2 Kinematic ones don't bounce off each other without IsTrigger

#

But I don't know if that interferes with your other setup.

#

You can also make a shadow ball clone which is invisible with this setup and read the collisions from that.

real talon
signal osprey
real talon
#

isKinematic Controls whether physics affects the rigidbody.

#

And since you move with the rb.velocity you can't use it. Then the only option I think is the shadow clone.
Or you ditch the sphere altogether and just use the racket and add the bounce off mechanic from there 😉

meager kite
#

is it better practice to load JSON data in Awake() or Start()?

real talon
#

Start already rendered a frame

#

So Awake

meager kite
#

alright thanks

signal osprey
somber swift
somber swift
regal olive
#

any idea why the meshcombine example in the docs isnt working

grim dew
#

hey @here, can anyone explain this behaviour? I basically have four identical gameobjects, and they each have the same monobehaviour script attached. the script looks like this:

public class GameEvents : MonoBehaviour
{
    public static int instanceNumber = 0;
    public static GameEvents instance;
    public int instanceNo = 0;

    public GameEvents(){
        print("Creating GameEvent!");
        instanceNumber += 1;
        instanceNo = instanceNumber;
        instance = this;
    }

    private void Awake(){
        Debug.Log($"Running Awake on Gameobject name: {this.gameObject.name}");
        Debug.Log($"Instance Number on Awake(): {this.instanceNo}, Gameobject name: {this.gameObject.name}");
    }
...

In the script, there is a constructor which iterates a static int so I can see how many instances there are, and on the scripts awake it tells me the name and instance number of the script I am working with. I also have a button on the screen that when pressed, will give me GameEvents.instance.instanceNumber, so I know the instance number of the static instance being stored. The reason why I am asking this is because I had assumed what would happen is that when the game is run, I would get "Creating GameEvent!" in the console four times, before getting the debug.log stuff from the Awake() method** in the order in which the scripts appeared in the project hierarchy**. Instead, what I get is "Creating GameEvent!" once in the console, before the awake debugs.log run, but regardless of the order of where the scripts were placed in the project hierarchy,** it will always run in such a way such that the awake of the fourth instance is run first, before it goes down to the first instance**. Additionally, if I put the monobehaviour scripts in chronological order with the order of the gameobjects in the hierarchy, the instance number of the GameEvents instance object will be 2, but if i put it in reverse order to the hierarchy, it will be 3.

#

Can anyone explain any of these behaviours?

real talon
fresh salmon
#

@here

#

Trying to ping a lot of users here

#

25196 to be precise

grim dew
#

Not sure I understand the last thing you said in the context of what I've written though

grim dew
fresh salmon
#

Fortunately these are disabled, like the dreaded @everyone

obsidian glade
real talon
#

So yeah, I would explain this as really logical code, every instanceNo is 1, exactly what I would expect after the increase of 1 from 0.

grim dew
urban warren
grim dew
urban warren
#

You don't want to use Constructor for classes that inherit from UnityEngine.Object as was already stated.

grim dew
obsidian glade
#

destructors are also something to avoid on Unity objects - prefer OnDestroy

real talon
#

public static int InstanceCount { get; private set; } is cool though, did not know this was allowed.

real talon
urban warren
severe grove
#

I'm back with a new idea and I have no idea if there is a way to do it. So, in order to create and use scriptable objects, we have to create a script and then we create an instance of that script through create asset menu. Hypothetically, say that we don't care about the resulting object being editable in editor. Is there a way to skip the middle man and have a structure to store data that we can write in script and reference without requiring a constructor? I was thinking something like extending an abstract class with a static class but that cannot be done in c#.

grim dew
#

Ah okay fair enough. I think moving them to Awake() and OnDestroy seemed to make things behave as I'd expect. I think it would be interesting to figure out what exactly unity is doing that causes the weirdness with constructors but ill leave it for now. Thanks guys!

urban warren
severe grove
# obsidian glade like a text file?

I don't think that would work. I don't want just storing data but storing functions too. Essentially I want a scriptable object I don't have to instance and is static.

urban warren
severe grove
obsidian glade
severe grove
#

Static classes cannot extend abstract classes.

severe grove
#

I had been under the impression it would be lazy and load as needed.

obsidian glade
#

they are loaded in the CLR when first used afaik

#

but then persist until application close

urban warren
#

Yeah

severe grove
#

interesting

grim dew
#

Does anyone have any info on how different data structures are stored in memory?

#

or rather links to resources that explain how different data structures are stored in memory?

timber flame
#

There are a bunch of buildings. Each building has an int id.
To keep them in a 3d array, ids are used.
My problem is how I should define and distinguish between these buildings.
If I define id as a key with enum type, it is more readable. In scripts, they can be used and accessed with enum names instead of raw int values. The drawback of enum is that values have only one level hierarchy. They come one after another.
Another approach is to define unique string in addition to int id as well. Here, the values can be nested like building/office/medical/..
but I have to create another dictionary with string key in addition to main dictionary with int id key to find that asset as fast as possible by unique string name.

Main Dictionary<int,Building>      id -> building

Dictionary<string,Building>      unique_name -> building
or
Dictionary<string,int>      unique_name -> id (map name to id)

What is your opinion?

Totally, I need int id for each building because they are stored as an int value in 3d array and I would like to access their info/definition data using strings/enums in scripts instead of raw int values.
Option 1: enum ids

Building10:
  Id: Building10 (10)
  //...

Option 2: int ids + string unique name

Building10:
  Id: 10
  Name: "Building/Building10"
  //...
late jackal
#

Hey guys!

#

Im having problems executing a bash script from inside unity editor. When I debug log the output it gives me nothing. What do i do?

urban warren
timber flame
#

Suppose, both, code and from the inspector.

#

but we know they can be props in the inspector finally.

public class RailRoadBuilder:MonoBehaviour{
   [SerializeField] private string _straightRailName;
   [SerializeField] private string _curvedRailName;
  //...
  private void Start(){
     var railRoad = _buildingRepository.GetByName(_straightRailName);
     //...
  }
}
urban warren
#

I had a sort of similar issue to solve. What I did was create a simple node tree, with each node having a name and an id.
The tree is stored in an SO that is loaded, and every node is put in to a id > node dictionary.
Then I have a custom struct that stores an id. This way I can use either the name or the id to get a node. And the struct will cache the reference to the node when it is first gotten. This prevents you from having to deal with mistyping strings.

#

Of course this isn't exactly the same as your situation as I wanted to access the hierarchy (the parent or child nodes)

timber flame
#

Then I have a custom struct that stores an id. This way I can use either the name or the id to get a node.

#

I did not get it

#

You had created two dictionaries for id and name keys or ?

#

map id to string?

urban warren
#

For the name I traverse the tree from the root.

timber flame
#

or none of them. simply search linearly by name O(n)

timber flame
#

I decided to include int id and string unique names for each asset.
Only create one dictionary with id key and asset value because I need to access data by id as fast as possible. (3d array is large)
but to build some stuff by name e.g. a road, it is not required to get data efficiently. If I need, add the second dictionary

#

To avoid mistyping about string names, I utilize odin inspector, create an enumerable valid string names and custom list for it

undone coral
#

as prefabs

#

there's no cost to referencing a prefab, and you can use the reference as a key

#

in a dictionary, if you'd like

round wharf
#

How would i make another player copy my movements?

fading nacelle
#

why does the editor eat up more and more CPU over time? Works fine at first and then expands exponentially. Is there a memory leak error in 2021.3.2f1?

orchid marsh
fading nacelle
#

runs fine at first then slows down

orchid marsh
#

So there's an extremely high probability that it's something that you're doing with an Editor script.

fading nacelle
#

hm interesting, best guess is something residual from obicloth (although it's not currently implemented anywhere)

severe grove
#

Is there a way to give this function a unique id that it will return every time? If I use Guid ID = Guid.NewGuid() it will generate a new guid every time it is called.```
public static Func<RSkill> Skill = () => new RSkill()
{
label = "Aether Manipulation",

        description = "You gain a pool of Aether Points which are used to perform Magic skills." + 
                      "\n\n" + "[color=green]" + 
                      "Aether = INT x 5" + "\n" + 
                      "Can equip Magic Foci" + "[/color]",
        
        useType = SkillUseType.Passive,
        targetType = SkillTargetType.Self,
        tags = new HashSet<SkillTag>()
        {

        },
        cost = new Dictionary<SkillResourceType, float>()
        {

        },
        isBase = true,
        isStarting = true,
        startingWeapon = null,
        unlockedSkills = new List<RSkill>()
        {

        },
        Execute = () =>
        {
            
        }
    };```
unkempt geyser
#

you could have a static dictionary of guids somewhere where you can check against some identifier (perhaps the label or a hash code?) to get/add a guid

#

if i had it my way though, i would just inherit an abstract class and implement those properties from there and use the class id or something

severe grove
rocky mica
#

cached dictionary also works

buoyant vine
manic stump
#

is anyone here able to help me with one of my scripts . It does work but i was wondering if there was a better way to do it cause it seems to run slowly.

peak tulip
#

@manic stump what are you trying to accomplish with the script? Just placing a bunch of starting items? Cause Instantiation is fairly costly in terms of what can be done in a single frame's time.

#

And you're creating 1400 things

manic stump
#

well im doing a fps game and im trying to place enemy and ammo boxes and medkits in random spots round the scene

peak tulip
#

Okay.. I wouldn't instantiate them all off the bat. If you want to pregen a bunch of different things. I would create 3 List<Vector3> one for each thing. Then just randomly gen the positions first. Then, when a player approaches and can actually see them, Instantiate it

#

saves a TON of time

manic stump
#

how would i do this im still new to unity

peak tulip
#

I'd follow some initial unity tutorials tbh. If you're not familiar with the engine yet or OOP in general, do as many as you can. It really helps

manic stump
#

what topic would i try to google i have seen so many tutorials i would not know where to start

peak tulip
#

then just use a codeacademy type reousrce ot learn more oop

manic stump
#

does that cost money?

peak tulip
#

not at all

manic stump
#

k ill look into it thx

meager kite
#

CodeAcademy costs money for anything past the basics iirc

slow fox
#

For some reason my script won't get past the WaitForSeconds. It outputs everything in the debugger before that, but nothing after

    {
        Debug.Log("We have started the slow down script");


        if (!slowDownActive)
        {
            slowDownActive = true;

            GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");

            //Tell enemies to slow down
            for (int i = 0; i < enemies.Length; i++)
            {
                GhostFace enemyScript = enemies[i].GetComponent<GhostFace>();
                enemyScript.SlowDownTime();
                Debug.Log("Slowing down for ghosties");
            }

            Debug.Log("Made it to the counter");
            yield return new WaitForSeconds(slowDownLength);

            Debug.Log("WaitForSeconds completed successfully");

            for (int i = 0; i < enemies.Length; i++)
            {
                GhostFace enemyScript = enemies[i].GetComponent<GhostFace>();
                enemyScript.BackToNormalTime();
                Debug.Log("Back to normal time");
                slowDownActive = false;
            }
        }
    }```
devout hare
#

Either slowDownLength is very large, or you destroy the object this script is on

slow fox
#

It's pretty short and I made sure that the script won't be destroyed even on reload



//Makes sure the GameManager is kept between scenes. If there isn't one, then create it
        DontDestroyOnLoad(gameObject);

        if (instance != null && instance != this)
            Destroy(this.gameObject);
        else
        {
            instance = this;
        }```
#

Sorry, I should specify, the don't destroy on load runs at start

devout hare
#

That looks a lot like destroying the object

slow fox
#

Should only destroy it if at start another version exists

devout hare
#

Well, the coroutine is destroyed because the object is destroyed. You'll just have to find out why that happens.

slow fox
#

That's weird, any idea why it would output
Debug.Log("Made it to the counter");
but then hang on the WaitForSeconds? I don't have StopCoroutine or StopAllCoroutines anywhere in my code, so not sure why it would stop

devout hare
#

because the object is destroyed while it's waiting

slow fox
#

Sorry, just wanna make sure I understand. Do you mean that because it's waiting it's being destroyed, or that some other script is destroying it while it's waiting?

devout hare
#

The coroutine stops because the gameobject that it's attached to is destroyed, for reasons unknown

slow fox
#

I'll take a look around and see if I can confirm whether it's being destroyed or staying up. Thanks!

plucky hound
#

Good morning everyone! Stay hydrated!

slow fox
#

AH you're right @devout hare
It wasn't destroying the gameobject with the script, but because the script that started the coroutine died, it was cancelling it. This is the gameobject that was starting the coroutine

    {
        Debug.Log("Me ghost, me ded");
        if (!timeSlowActive)
        StartCoroutine(gameManager.SlowDownEnemies());


        Destroy(this.gameObject);
    }```
#

Seriously appreciate the help!

devout hare
#

Right, the object that starts the coroutine is what's responsible for managing it

hardy jacinth
#

so yeah, this is now solved

spice wave
#
JsonUtility.FromJson<PlayerConnectionData>(Encoding.ASCII.GetString(connectionData));```
This is where the server takes the connectionData byte[] and converts it to my class which just contains a string called username. Whenever I use username it always has a "?" at the end, so say my username was Test, it would look like: Test? Does anyone know how to fix it?
formal lichen
#

is there some end of line delineator being added?

spice wave
#

I am not sure, its the first time I worked with encoding like this, but just encoding the string and back in the same line does it as well

formal lichen
#

is the encoding ascii on both ends?

#

one could be unicode

#

could try utf8, I think that's compatible between both

spice wave
#

Ill try UTF8, the encoding is ascii on both ends

#

nvm, utf8 works. thanks!

stuck onyx
#

I have a List<SimpleClass> myList this classes have
-int soID (not unique)
-boolÂĄ completed

I want to check if there are > 1 item with the same soID and not completed
Im trying to do it by Linq but dont know how to separate them by soID

#

I'd like something like:

myList.Where(x=> (same soID) && completed==false).Count > 1````
late jackal
#

hey guys does anyone know how to call a bash script thru unity

undone coral
late jackal
#

im trying to create a dotnet console project (VS project) and make the script the automates that process run in unity

undone coral
undone coral
#

what is the script?

#

what's the objective? like what does it do

late jackal
#

it creates a dotnet project and gets all the files it needs from a sppecific directory and then build it so i could get the .xml documentation in the build

#

because in unity i cant do that

undone coral
late jackal
#

it works in the terminal perfectly i just cant run it in unity

late jackal
#

when i try it outputs nothing

#

yes

undone coral
#

i am trying to understand what it is you're trying to do

#

maybe give me the big picture

#

i'm sure you've googled "how to start a process c#"

#

so i don't think that's your issue

late jackal
#

in general im trying to create an automatted documentation system. its finished but in order to do so i need the xml of a package then i parse thru all the xml comments and create documentation for any unity package. Before this script people had to do like a 10 min process to build the package and get the .xml documentation. So the script runs and does all the for u now but i want to run it in unity because some people dont know the terminal well in my company

undone coral
late jackal
#

yea i did that but the process runs but outputs nothing so im not sure its actually doing it

undone coral
#

i don't know what the script is supposed to do yet

late jackal
#

my question also which might be the problem is does unity actually execute it in the macos terminal or is it unitys own

#

ill show u

undone coral
#

it's a script that takes a file directory as an input and writes files somewhere?

late jackal
#

yea it takes the original package directory and the directory u want to output the new project

undone coral
#

you authored the bash script?

#

can you paste the first 3 lines of the script?

#

i don't need to see the whole thing

late jackal
#

yes i did

#

and ok

undone coral
#

it's going to communicate to me how well you know what's going on

late jackal
#

cd ${NEW_PROJECT_DIRECTORY}
mkdir ./${PACKAGE_NAME}
cd ./${PACKAGE_NAME}
dotnet new console -n ${PACKAGE_NAME} -o .

late jackal
#

thats the beiginning

undone coral
#

how many lines is it?

late jackal
#

like 30

undone coral
#

okay

#

these are really the first 3 lines?

#

i want the real first 3 lines

late jackal
#

yea i mean the first lines are variables

undone coral
#

well...

#

i need to see

#

literally

#

line 0, line 1, line 2

late jackal
#

#!/bin/sh
#Variables
PACKAGE_NAME=$1
ORIGINAL_PACKAGE_DIRECTORY=$2
NEW_PROJECT_DIRECTORY=$3

undone coral
#

okay

#

so you have a few options

#

you can (1) try to make this script robust enough to make sense to run from unity

#

(2) rewrite its behavior in c#

late jackal
#

and i was asking the first question cause i had to install dotnet command on terminal so thats why im like do i have to do something for that to work in unity

undone coral
late jackal
#

what do u mean more robust

#

or rewrite behavior?

undone coral
#

hmm

#

sorry about being imprecise here. robust means that based on the beginning of your script, i can tell you don't know enough about bash scripting or writing these sorts of short utility programs to know how to make them callable from other programs in a general way

#

rewrite its behavior means you would create a function in c# that does all the things that this script does

#

you should probably be using Rider instead of VS Code

#

and you have to install the shellcheck plugin

late jackal
#

yea i mean i just know how to call in the terminal

#

i cant use rider in my company

undone coral
#

i see

late jackal
#

and i need the shell check package for unity?

undone coral
#

no

#

it's a plugin for rider

late jackal
#

oh

undone coral
#

so really creating a new process in c# is so straightforward

#

it's so well documented online

#

i think what is confusing to you is that the program you need to run is /bin/bash

#

with the argument that is your script

late jackal
#

i made the process tho

undone coral
#

followed by the other arguments

#

but the positions are going to be wrong

#

surely this was online though

late jackal
#

and i did what people say online its just not outputing anything

#

no error or anything

undone coral
#

it's on the first result for me

#

"how to start a bash script from csharp"

#

there's a lot here

#

i don't mean to give you a hard time

#

but i'm trying ot understand what the actual issue is

#

you are running into a pitfall regarding the bash argument positions

late jackal
#

but in this example its a command and not like a script

#

no like this is it

undone coral
#

here's another example

#

my suggestion is to rewrite the script in c#

#

it will take you less time than diagnosing this

#

i don't know what the end goal is though, because if your colleagues can't run a command from terminal

#

well they're not going to be able to install dotnet, nor the package that you're using to read the doc comments

#

it sounds like your goal is "produce documentation for people"

#

it's confusing why though?

#

why do they need the documentation from here?

late jackal
#

no they can install i mean dotnet and my package is a unity package so its fine

undone coral
#

someone who can't program or use the terminal, what use are comment documentations

#

well how do you think they install dotnet?

late jackal
#

but i mean i dont want to harcode the commands u know

#

i mean i only need one person to

undone coral
#

so

#

i don't know none of this makes sense

late jackal
#

but like im just trying to make the process as easy as possible

undone coral
#

you can also just commit the files it outputs to source control?

#

why does there need to be a script at all

#

i don't know what would consume doxygen output

late jackal
#

no i dont want that

undone coral
#

well... why not?

#

what would be the consequence really?

late jackal
#

because i dont want specific information on git

undone coral
#

is it because vs code is not showing inline documentation correctly?

undone coral
late jackal
#

it doesnt show inline documentation for unity packages

undone coral
late jackal
#

its not possible so i created the script to do it or else its like 10 min of bs

undone coral
#

"vs code does not show inline documentation for unity packages" ?

late jackal
#

yea but its not a problem anymore cause the script does it

undone coral
#

i'm not trying to give you a hard time

late jackal
#

no i know im just trying to explain

undone coral
#

so why are you using this absolute dogshit editor?

late jackal
#

VS?

undone coral
#

yes, vs code

late jackal
#

i mean its vs pro

#

and its a problem in all editor

undone coral
#

you have to use rider

#

not in rider

late jackal
#

because unity has specific referneces

#

no yes in rider

#

ive done it

#

you can create .xml in rider for a unity package

#

it wont work without all the refernecs

#

cant

#

so i like copy the refernces and put it inthe new dotnet

#

creating a solo project instead of a package works so thats why i have to go thru all the bs

undone coral
#

well i suppose file a bug with rider

#

they'll fix it

late jackal
#

but i dont need that

#

i need to just run the bash script

#

like i have a solution already

undone coral
#

i think you should be able to run it using new process

#

the alternative is i write this bash script for you

#

or you rewrite the thing the script does in C#

#

there aren't any tricks to diagnosing this.

#

your issue right now is the process you should run is /bin/bash, the second argument is the path to the script, the third+ are your regular arguments, and you need to set the working directory correctly

#

you can redirect standard out somewhere. but then you have to know what that means

#

you've probably set PATH incorrectly. you can always use an absolute path to the dotnet binary

#

which is probably another issue

#

do you see what i mean? all of this is just flaws in trying to do this with a script

undone coral
#

do you mean the Skill function or Execute

unkempt geyser
#

its for the skill

#

they already got a solution for that though

undone coral
undone coral
#

he can't call new guid

#

i think he was having a brain fart

#

a guid also wasn't used anywhere in his snippet so i have no idea what he means

late jackal
#

yes i see what u mean thank you. I have done it with the process command and added the arguments with that with psi.arguments and when i redirect the standardf output theres nothing so im just trying to get a you know error or something. definently cant give u the full script but thanks for offering. i made the psi.filename also "/bin/bash" and gave the actual filename with arguments in the process too. I use absolute paths but can you point me in the direction of how to write the script so it wont be confused. should i delete the variable lines?

#

also i do appreciate everything sorry if it comes across like im not im just stressed and been stuck on it a while

undone coral
#

it's just tough because it's not your fault unity doesn't create these files

#

you sould probably rewrite it in c#

#

it will be faster to do this

#

and you'll be more aware of what's going on

daring pelican
#

hey guys, does anyone know why cocoapods would fail to install on mac?

#

im mostly a windows user, can't figure it out

undone coral
#

you can't really do sudo gem install cocoapods

#

is that what you did?

daring pelican
#

yeah i did that

#

it's saying that ruby is not in my path

#

no. sorry, first i try sudo gem install cocoapods

#

it says i don't have write permission

#

then i try "gem install cocoapods --user-install"

#

and it says that [path to bin] is not in my path, executable won't run

#

iOS resolver in the project fails, so i figured i gotta install this thing in the system first?

late jackal
#

@undone coral so thank you i actually got the bash script to run. but my dotnet commands dont run in the script. Is there something i have to do to get dotnet recognized by unity

undone coral
#

because it's just a bunch of arbitrary stuff

undone coral
#

the issue is that you are using .bashrc or .profile to modify your PATH

#

you can add the argument -l to /bin/bash to make it load your .profile, but that's not going to work on the other user's computer

#

does this make sense?

late jackal
#

yea it does. so what would be my best option? To tell people to have it in the same place?

#

everyone should have it in : /usr/local/bin/dotnet? and run it with that

undone coral
#

so it will be there

nocturne osprey
#

have anyone seen this error before ?

Missing shader. PostProcessPass render pass will not execute. Check for missing reference in the renderer resources.
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
undone coral
late jackal
#

thank you @undone coral I did it!! tyty

hazy epoch
#

Is there something about building using Dedicated Server that would cause collisions and triggers to not work on nested colliders?

undone coral
#

it might strip meshes

hazy epoch
meager kite
#

is there a way to debug every float in your script via algorithm, instead of specifying every single float individually?

sly grove
undone coral
#

i wouldn't recommend using the dedicated server checkmark

hazy epoch
sand raven
#

im getting an issue with microsoft visual studio: whenever I open an error from the console to bring me to where the error is, even if the script in question is already open, MVS reloads the whole project, and its really slowing things down

sand raven
#

from looking at what it does in the bottom left, it apperently unloads, then reloads the project for some reason?

sand raven
untold moth
sand raven
#

sorry, it didnt get the bottom part

untold moth
# sand raven

The important part is that the assembly shows up properly ("assemply-csharp"). That means that it is configured properly.

untold moth
#

That too, but mainly the top-left part that shows what assembly the script belongs too.

#

Can you take a screenshot of your unity editor - preferences - extarnal tools tab as well?

sand raven
untold moth
# sand raven

Does that vs version correspond to what you're actually using?

#

Try unchecking all the tickboxes and regenerating project files as well.

sand raven
#

yes, and yeah let me try that

#

that seems like its fixed it, but ill let you know if it happens again.
Thanks dilch

covert rain
#

Obviously it isnt actual syntax but you get what i mean right?

misty glade
unkempt geyser
misty glade
#

Gotcha. I also noted they make a lot of references to Mono which .. as far as I understand .. is arms-length from Unity, no? (I'm using IL2CPP anyway fwiw)

unkempt geyser
#

mono is just a .net implementation that unity just happens to use. it does talk a bit about how mono's gc is a bit lacking speed-wise which does unity still use, but i wouldnt consider that to be unity's fault but rather mono's

quick sand
#

Hello guys, i have this complicated issues with Vs and unity at the same time, Its hard to explain so id like to vc with someone later today, anyone wanne help?

#

If your comfy with vc ofcourse.

maiden turtle
#

Hi, how come sharedMesh.vertices.length is different from sharedMesh.vertexCount?

#

That is the mesh

#

Oh, is it because of Read/Write

#

Yes, it's because of Read/Write, nevermind

rapid flume
#

hello guys can anyone tell me how to shoot gameObjects(bullets) from my gun in unity, and btw not using raycasting only the gameobjects collider

shadow seal
rapid flume
shadow seal
#

Coming from the Latin Instantia it means "represent as or by an instance". Which in Unity terms just means it creates an object

shadow seal
#

We're in #archived-code-advanced I would expect you to know about Instantiate really, and at least Google it yourself

rapid flume
rapid flume
rapid flume
manic stump
#

is this the right place to get code help about navmeshes

misty glade
#

perhaps, probably depends on your question.. use your best judgement 🙂 the answers you get here might be a lot more high level, where you're expected to know how to do something at a nuts and bolts level

#

if you're going to ask what Instantiate() does you might have a bad time

manic stump
#

no it not that i know how to do that

misty glade
#

probably just go ahead and ask then and if it's the wrong place, someone will (gently or not) tell you where to go 🙂

manic stump
#

i just having problems where i use a raycast to find the navmesh so i can try to spawn an enemy prefab on it but it does not work properly

#

should i show the whole code or just where is goes wrong

misty glade
#

both, probably - discord is good for 5ish lines of code at most, if you think you need to show more, use pastebin.com

#

and also don't repeat characters in your messages or the bot will auto delete it 🙂 like you probably just found out

manic stump
#

it spawns them ok but how would i have it check what the raycast hit before it puts them in the scene if it hits the ground not a tree etc

misty glade
#

so probably more of a question for #archived-code-general or #💻┃code-beginner , but if you check into the API docs, the raycast method has properties that you can enumerate through to see what's been hit.. i think the collection is literally called collisions

#

(this is the type of answer you'll get here - "use the collsions collection returned in the Raycast() call", whereas the answer in general or beginner is much more likely to contain actual lines of source code you can copy or modify)

manic stump
#

ok ty

misty glade
#

also .. just in general, your block of code is confusing because of your lines 4/5 - if you don't use braces with if statements, then indent the next line or put it on the same line, because it's not obvious at a glance that line 5 is in the if statement

#

and maybe that's a bug

#
// do this
if (thing == thing)
{
    DoThing();
}
DoNextThing();

// or this
if (thing == thing) DoThing();
DoNextThing();

// or this
if (thing == thing)
    DoThing();
DoNextThing()

// don't do this
if (thing == thing)
DoThing(); // <-- bad
DoNextThing();
manic stump
#

ty again

hallow elk
#

Is there a way to have a component run a method when a scene is loaded in Edit mode?

#

I have a script that updates some things when scenes are loaded or unloaded additively. It'd be useful to be able to see those changes in Editor when the scenes are loaded, rather than having to go back to that script and click a button to trigger the script

misty glade
#

example from my codebase:

#
#if UNITY_EDITOR
        private void OnValidate()
        {
            UnityEditor.EditorApplication.delayCall += OnValidateCallback;
        }

        private void OnValidateCallback()
        {
            if (this == null)
            {
                UnityEditor.EditorApplication.delayCall -= OnValidateCallback;
                return; // MissingRefException if managed in the editor - uses the overloaded Unity == operator.
            }
            InitializeComponents();
            DoLayout();
        }
#endif
#

I use the delayCall .. because.. I can't remember the exact reason but there's some unity oddity where it starts spamming you with error messages if it tries to do stuff in the same tick - you have to do it a frame later (in the editor)

#

this will also run anytime the gameobject it's attached to is modified, so .. if you start moving the actual game object around your scene you're gonna get a lot of these calls

hallow elk
#

I do something similar with EditorApplication.heirarchyChanged, but it's not working

true cosmos
#

Got a problem wih unity test framework. I have multiple tests that basically start the whole game from scratch using [UnitySetUp] and clean up scenes using [UnityTearDown]. These tests work when runned separately, but they fail randomly when called with "Run All". There are MissingRefExceptions everywhere and it happens at random. What i might be doing wrong? it seems unity doesnt clear all objects or keeps invalid refs in between tests 😭

misty glade
#

like doing it a frame later

misty glade
hallow elk
#

I have:

#if UNITY_EDITOR
        void OnHierarchyChanged() => UnityEditor.EditorApplication.hierarchyChanged += OnHierarchyChangedCallback;
        void OnHierarchyChangedCallback() => UpdateSceneItems();
#endif
misty glade
#

yeah so I'd use delaycall

#

(instead of hierarchychanged)

#

i've never tested order of operations (or even used hierarchychanged) but it might be getting called before your hierarchy is fully loaded, so if your script is fiddling with other things that are supposed to be in the scene, it might not find them?

#

delaycall runs at the end of an update tick

hallow elk
#

I've changed it to delaycall, but it still isn't running

misty glade
#

put it in OnValidate

#

oh

#

check to make sure this isn't null and if it is, delete the callback and abort

#
void OnValidate() => UnityEditor.EditorApplication.delayCall += OnDelayCallback;
void OnDelayCallback()
{
    if (this == null) 
    {
        UnityEditor.EditorApplication.delayCall -= OnDelayCallback;
        return;
    }
    .. do init here ..
}
hallow elk
#

Ah! I was being dumb. The first part needed to be the class name. I'm a dummy

#

Thanks @misty glade

misty glade
#

np toast

#

😉

regal olive
#

imma need to use the legacy ui is it gonna be removed shortly?

somber swift
#

most likely neither will be removed in few next years

crystal wasp
#

is it possible to use "exist", or "for-all quantifiers" in c#/c++?

crystal wasp
# obsidian glade yes

i assume there are reserved keywords like "for" for the quantifiers? siince theres no shortcut. i cant find any infos on that. like foreach and except? but you cant use foreach in constructor

obsidian glade
#

there's core language features like foreach and a lot of extra query tools for enumerables in the System.Linq namespace

#

what are you trying to do?

regal olive
#

before the ui toolkit

#

cause the ui toolkit input is not very customizable

crystal wasp
somber swift
# regal olive before the ui toolkit

Ah, thats going to last many years I believe. Only very recently they added even possibility to use the ui toolkit for runtime uis and the ui toolkit is far from ready, they are still adding ton of festures to it. The ”old” ui system being legacy means unity is most likely not going to add many new features to it anymore (which they havent done earlier either afaik. Other than tmpro being added, i dont remember any features they have added in the past few years. correct me if im wrong, most likely i have missed something obvious). Also if youre not going to upgrade to newer unity version during the project, you dont need to worry because unity will not remove it from existing versions but instead not support it by default in the future versions (will take few years i think). Even then you could most likely use the old ui by installing the package and maybe do some extra set upping. So id use the legacy ui, no need to worry at this point

obsidian glade
#

I imagine not the route you want to take for learning about semaphores though

rough gazelle
#

Has anyone else noticed that task cancellation (async/await) has become asynchronous somewhere between 2021.0 and 2021.3? At least in some situations, if you await on a task that will be canceled, the cancellation doesn't process synchronously, but instead later in the same frame. I reported this as a bug over a month ago, but haven't yet gotten a response. Wondering if it's actually a bug or intentional for some reason.

misty glade
rough gazelle
#

...when everything is happening on the main thread, that is.

misty glade
#

which .NET? I know cancellation tokens and behaviour changed in .net6

#

i don't recall exactly what, though, i don't really cancel my tasks 🙂

hallow elk
misty glade
misty glade
#

the if this == null part

hallow elk
rough gazelle
misty glade
hallow elk
#

ok...going to try it

misty glade
#

Change to:

#if UNITY_EDITOR
    PersistenceManager() => EditorApplication.hierarchyChanged += OnHierarchyChangedCallback;
    void OnHierarchyChangedCallback()
    {
        if (this == null) 
        {
          EditorApplication.hierarchyChanged -= OnHierarchyChangedCallback;
          return;
        }
        UpdateSceneItems();
    }
#endif
#

also strongly suggest (as before) that you use .delayCall instead of .hierarchyChanged because you'll get some hard-to-figure-out bugs if the hierarchy is incomplete (i believe)

rough gazelle
#

@misty glade seems to be the same on at least netcoreapp3.1, .NET 6 and older Unity versions, just different on 2021.

misty glade
#

ok so .. await doesn't break as soon as a task is canceled (weird, right?) - so I think what you need to do is literally create the task from the call, create a cancellation token, and then try/catch yourTask.Wait(yourCancellationToken);

#
CancellationToken cancelToken = new CancellationTokenSource().Token;
Task t = Task.Run( () => { YourMethodAsync(); });
try
{
  t.Wait(cancelToken);
}
catch (OperationCanceledException)
{
 ...
}
#

or something, I dunno, maybe that's butchered

hallow elk
#

I am having a serious issue: Unity keeps changing the capitalization of a script name. When this happens, it breaks the connection with Inspector. I have to go through and rename this file every single time I start Unity.

rough gazelle
misty glade
misty glade
hallow elk
#

I don't have that option, this script is one of the major components of the game.

misty glade
#

i think alternatively you can rename it in unity and it should fix it.. but yeah, never edit the files outside of unity, shit breaks that way

hallow elk
#

Renaming it in unity fixes it until I restart unity, then Unity puts it back

misty glade
#

try renaming it in unity and then rebuilding the asset library.. i don't think the meta files have the name of the script in them but I don't know where else that might be embedded

#

assets/Reimport All

#

it'll give you a scary sounding dialog then chug away for a few minutes

crystal wasp
obsidian glade
#

if you write your own compiler maybe - you can take some shortcuts with aliases but changing the structure of the syntax is another issue

crystal wasp
#

yea thats the topic: compiler^^. but i just wanted to understand the basics here. thank you bro!

fresh salmon
#

Code snippets can turn some characters into fully-fledged pieces of code
But from what I understand, this means "if all elements of the set are true and [something else]", which can be achieved with LINQ

#

if (els.All(e => e) && ...), where els is any collection of bool values

crystal wasp
# obsidian glade if you write your own compiler maybe - you can take some shortcuts with aliases ...

https://en.wikipedia.org/wiki/Typedef found it. but its not c# though

typedef is a reserved keyword in the programming languages C and C++. It is used to create an additional name (alias) for another data type, but does not create a new type, except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type. As such, it is often used to simpli...

fresh salmon
#

Oh we can do that in C#, where the using statements are.

using MyDebug = UnityEngine.Debug;
#

It makes an alias for the type

obsidian glade
#

it also doesn't do what you described you wanted it to 🤷‍♂️

undone coral
#

looks like lambda calculus

#

but it's not

undone coral
obsidian glade
# undone coral i have no idea what this is

it's pseudocode with a mix of mathematical symbols and C/C++ where ∀i: means "for all i such that", that translates effectively to what SPR2 said: if (so.s.All(e => e) && ...)

obsidian glade
#

not mine - I've been wondering the same thing about the original question

undone coral
#

a semaphore example

#

ah

#

that's right

#

that's what @crystal wasp wanted, a semaphore example?

crystal wasp
undone coral
#

you'd have to share the class

crystal wasp
misty glade
undone coral
misty glade
#

...... I didn't know there was one? 😛

#

have to run to kids soccer but link me, i'll check it out when i return

undone coral
misty glade
#

Only skimmed it, but I think this is different? Mines weighted and has functionality to draw items randomly by weight.

misty glade
#

It was fun

rough gazelle
# undone coral you can't use bog standard c# async in unity robustly. use unitask

Thanks for the suggestion, but my use case is pretty far from typical: it's a testing library that also works with .NET. I want to avoid adding a dependency to UniTask, and want to keep using standard .NET tools during development, which are not available for Unity (like running tests & coverage automatically in Rider on every save, stryker.net mutation testing). Also, due to its nature, avoiding allocations is not really a top priority.

kind ivy
#

i am using netfish network and when the player spawn how do i spawn it on the exact position
so far it is not appearing

onyx blade
#

Could anyone explain to me how the AR Plane (AR Foundation) can be changed into a more "clean" (or project specific) visualisation? The default unity plane isn't that visually pleasing, but I can't find out how to change it (or more specifically what to change it to...)

maiden turtle
maiden turtle
#

What's the standard way that I should use to get Span from List?

#

In unity

#

I have imported System.Memory

austere jewel
#

Using range syntax is usually how you get spans

maiden turtle
#

??

#

Range syntax only gives spans if you use it on spans

#

On arrays it gives arrays

#

On lists afaik it's not usable at all

austere jewel
#

you do .AsSpan() and then use range syntax

maiden turtle
#

That's for arrays, not lists

#

There's no AsSpan for lists

#

Apart from that, reflection hacks

austere jewel
#

That's your answer 👍

maiden turtle
#

Is there really no way to do it normally?

austere jewel
maiden turtle
#

Well obviously

#

Unsafe is what I'm looking for

austere jewel
maiden turtle
#

Also, shouldn't you cache that?

austere jewel
#

I mean, it won't work with IL2CPP, but yes, once it's compiled it should be faster—and it is cached

maiden turtle
#

Never used that lambda stuff

#
public static class ListExtensions
    {
        private class Info<T>
        {
            public static readonly FieldInfo ItemsField = typeof(List<T>).GetField("_items", BindingFlags.Instance | BindingFlags.NonPublic);
        }
        
        // NOTE:
        // One must not add or remove the elements from the list.
        // There might be problems with GC if you do.
        public static Span<T> AsTemporarySpan<T>(this List<T> list)
        {
            Assert.IsNotNull(list);
            var items = Info<T>.ItemsField.GetValue(list);
            Assert.IsNotNull(items);
            return (T[]) items;
        }
#

I just did this for now

maiden turtle
#

Ah yeah I need to slice it

#

Forgot about that

silver schooner
#

I'm trying to add a simple culling system to my game where I have trigger volumes that contain a list of objects they should hide when the player is inside them, and I was wondering how best to implement this.

Specifically, I have a house with various rooms, and all the objects in each room are contained within a parent object for that room, so I can hide or show them all by showing or hiding the parent object.

I could give each trigger two lists of objects, one to reveal and one to hide, and then have whichever trigger the player is inside of (assuming the player is defined by a point rather than their capsule which could span multiple volumes) show and hide every object in the list as necessary, but it seems a little absurd to have to list the objects I want to be visible, if that's their default state. I suppose it wouldn't be too much work to do this for my small house and a dozen volumes, but I was wondering if perhaps there was a better way... I suppose I could have one master list of objects in a controller which shows them all each frame before the other scripts hide them, though I'm not 100% certain that scripts will execute in the order I expect them to, which I guess would be the first scene, the first parent, the first child of that parent, and down the list recursively like that? Another thing I could do is have that object have a master list but have the volume read from it and show them itself and since it would be the only one executing since the player position could only be inside one volume, there would be no potential conflicts there. But that feels messier than it needs to be. I'd prefer to keep the objects accessing only their own data as much as possible.

Anyway, just looking for suggestions I guess for any methods I haven't thought of.

#

Oh, and I already tried Unity's built in culling system. It's awful. Barely culled anything no matter what settings I gave it. So that's why I decided to go this route. The game isn't very large so setting it up manually isn't that big a deal.

silver schooner
#

Hm... On further investigation it appears you can't count on Unity executing scripts on your objects in any particular order. The order in the hierarchy does not guarantee execution order. It's possible to set particular scripts to run in a particular order in the project settings but that sets a global priority for all scripts of that type. Though in this case I suppose it could be used to make a main script that unhides all objects in a list run before the ones that hide objects. Still, this seems like a bad way of going about it. Perhaps a better way would be to have one script that checks to see if the player is inside various volumes and then grab their list of objects to hide if the player is inside them and then have it hide the objects itself. Or I suppose it could call a method on the volume and tell it to hide its own list of objects. That might be better. This as opposed to having the individual volumes looking for whether a player has entered them and acting on their own.

obsidian glade
misty glade
#

why not have the objects just hide/unhide themselves? each object would have a list of rooms to show/hide in, and then based on what room you're in, the objects handle themselves

#
public enum RoomType
{
Kitchen,
LivingRoom,
Bedroom
}

public class InventoryItem : MonoBehaviour
{
  public List<RoomType> ShowInRoomws;
  public UpdateObject(RoomType currentRoom) => gameObject.SetActive(ShowInRooms.Contains(currentRoom));
}
#

@silver schooner

pale zinc
#

put a script on your parent gameobjects (e.g. Room) and have a second script called RoomCuller with a List<Room> with all the rooms in it. RoomCuller has a method public void ShowRoom(Room room) which goes through the list and does ForEach r.gameObject.SetActive(r == room)

pale zinc
#

volume calls that method on RoomCuller with a specific room.
Or Room has a reference to RoomCuller and calls it with itself as the argument

undone coral
#

it depends on your experience level. as you become more knowledgable about async await, you'll see that UniTask doesn't change much at all for the end user of a .net c# library.

silver schooner
# misty glade why not have the objects just hide/unhide themselves? each object would have a l...

Mmm... That feels like it would be less optimal. Every single object out of a couple hundred in the world would have need to have that additional component and be running a script constantly. In a small world with one house that might not matter much for performance, but its also more complex than it needs to be. And in a large open world, that method is definitely not optimal. You'd want some kinda system that group culls objects in that case. Which is kinda what I'm doing here with each room being a container for the objects that are all culled at once.

undone coral
#

the allocations story isn't essential. also as your experience level grows, you'll be able to read docs like those and understand that for a certain end user at a certain experience level, allocations is an important story for the purposes of adopting libraries into unity. but at a higher experience level, you can ignore notes like that because they're not meant for you.

misty glade
#

you could either

A) have a room publish an event that inventory items subscribe to (traditional events or UnityEvent)
B) have your .. game manager, player, whatever, detect when it's in a new room and iterate through all the currently held inventory objects and update their rooms, or whatever

undone coral
misty glade
#

basically you don't want to do much in Update() - especially for "state" changing things that only happen every few seconds to minutes, depending on your gameplay

undone coral
#

i know unity says it will adopt .net 6 AOT, but that isn't going to happen

#

the company says a lot of stuff

rough gazelle
undone coral
#

it's not a performance issue

misty glade
#

FWIW just to add to this - ARM64 (as far as I know) doesn't support mono and IL2CPP doesn't support AOT, unless that's what you meant unity said they'd do (add AOT to IL2CPP)

undone coral
#

it's possible they have already backtracked and removed that plan

misty glade
#

🤷‍♂️ could be - i'm pretty out of the loop with official unity comms channels.. there's just so much bleeping info

undone coral
#

you can use packages from nuget in unity, but you can't really use the tooling

#

again, this is just my opinion, but the value of the tooling is pretty low. i don't save much time being able to add and remove packages to a file

misty glade
#

drp: did you see my comments yesterday re: the java abstractbagmap thingy you linked me? my library is for weighted elements in a list

undone coral
#

it's okay to sort out the dlls and just drop them in and never think about it again

undone coral
misty glade
undone coral
#

i have some kind of weighted bag random pull implementation

#

i just haven't looked at it

misty glade
#

i did realize on thinking about it further that int for totalweight is probably insufficient.. if you had 1000 items with average weights around 2000, you could overflow

undone coral
misty glade
#

well i'm stinkin proud of the work I did on it so if you have time, take a look, like and subscribe, blah blah blah 🙂

#

O(1) get operations no matter how large the list is

undone coral
#

at a high enough level of expanding brain meme, you should see that testing in unity doesn't make sense

#

it just really depends on your experience level

#

like you don't need to use the unity editor to test packages. and most of the value of automated testing would be on target devices, like the iphone

#

but then... do you even use a mac?

#

do you see what i mean?

#

so if you're saying no to unitask, well, unitask provides value

#

it's just something to think about

#

if you can't see the value in it or getting a testing framework to be compatible with it, you might want to change directions

#

"code-advanced" perspective

rough gazelle
undone coral
#

let's buy you a mac 🙂

#

you will really thrive on one

#

it's time

#

it's 2022

#

this looks great

#

i also think you should try unitask

#

it resolves a lot of issues

#

at least study how it's implemented

rough gazelle
#

I have no idea why you're talking about macs, BTW, been working on one since 2015 also...

undone coral
#

it sounds like you are very visual studio

#

but i guess not 🙂

rough gazelle
#

Nope, Rider.

undone coral
#

that's great

#

i think at least take a look at how unitask is implemented

rough gazelle
#

I had the internals of Responsible written in UniRx, but then I rewrote it in async/await to support standard .NET 😄 If I was doing this in C++ I could consider typedefing and macroing the heck out of some parts, but i haven't found a nice way of supporting both on C#.

hallow elk
#

I wanted to confirm something: If I have a Monobehaviour with a Start or Update method, and I derive from that Monobehaviour, can I override the Start method? or do I have to create a new Start entirely?

rough gazelle
undone coral
#

you could in principle use an include to detect unitask, and do

using TTask<T> = UniTask<T>;

or whatever

rough gazelle
hallow elk
#

I can make Start virtual?!

hollow garden
#

yes

hallow elk
#

gaaaasp

#

ok

hollow garden
#

all Unity does is call a method named Start or something like that so it'll work

#

you can also make Start a coroutine

#

kinda cool

last bloom
#

Has anyone been able to use roslyn c# scripting in Unity 2021 to run dynamic code at runtime? I've been trying but I get NotImplementedException when I try the simplest C# expression evaluation. No idea how am I going to debug that.

sly grove
#

IL2CPP almost definitely doesn't support it

#

what's the use case? Mods?

last bloom
#

It's a experiment similar to the one that Sebastian Lague did with his coding game.

#

He used the CSharpCodeProvider which is even less supported I would guess.

#

Pretty sure I'm failing at the nuget import. Maybe wrong platform or something.

hallow elk
#

This might be a dumb question but...can you use Expression Body for unity messages? i.e.
private void Start => DoThisThing();

hollow garden
#

yes

#

why wouldn't you be able to

last bloom
#

yup, I do it for OnEnable with the new input system in some cases.

hallow elk
#

Well that's nifty. I'd been avoiding that because I wasn't sure.

last bloom
#

It's syntax sugar. It's not an lambda expression.

hollow garden
#
void A() => B();
``` is just short for ```cs
void A() 
{
  B();
}
sly grove
#

well lambdas are just syntax sugar too 😛

hollow garden
#

🤓

last bloom
#

I don't remember details but I've had problems with lambdas that just complicated stuff. It's been a while though.

#

Pretty sure it was scope stuff.

fresh salmon
#

Yeah, with captured variables it can mess logic up a bit

#

As it creates a class to hold them, if you change them before you call the lambda, the captured variable will also change

#
int i = 0;
Action<int> x = () => Debug.Log(i); // capture local i

i++;
x(); // logs 1
final hound
#

Here is my build configuration

misty glade
#

Hm.. definitely not the real problem, I built an APK (well, an AAB) with IL2CPP with Queues just a few minutes ago

#

did you resolve those "script not found" errors i can see peeking out?

long ivy
#

are you doing anything funny with reflection? maybe the type is being stripped. Try rebuilding with managed stripping level set to disabled

formal lichen
#

so you have to use mono to do this, which restricts your platforms to build to obviously too

flint geyser
#

https://blog.unity.com/technology/1k-update-calls
This web page illuminates how Update methods are called by Messaging System and it says
The thing is that these are the calls from native C++ land to managed C# land, they have a cost.
What is it referring to? As far as I know IL2CPP translates your C# scripts to IL and then to C++ for the targeted platform. In that case everything there should be in C++ without any calls to C#.

misty glade
#

he's referring to the cost of putting a method on the stack that does nothing

#

this is such a silly article, from my very quick read of it

flint geyser
#

😟

misty glade
#

aklsdjf;alskdjf i hate that bot

flint geyser
#

?

misty glade
#

i typed too many dots for a dramatic pause and the bot erased my message

#

This is a silly article because (dot.dot.dot.dot)..(pause).. he wants to have intellisense show reference counts to unity events?

#

Obviously if you subclass from monobehaviour and put something in Update() and then inherit from that in everything in your game it's gonna feel bad

flint geyser
misty glade
#

i mean, that's fair, but also.. obvious..?

#

I think people when they first start with unity do stuff like

public void Update()
{
  hitpoints.text = player.hitpoints.ToString();
}

not realizing that's horribly inefficient.. but also at the same time, it's maybe hard for a beginning programmer to understand pub/sub/event models or other ways of doing it

flint geyser
#

The only thing I am asking about is what are the "C++ to C# calls", if everything is in C++? (I think everything is in C++ because IL2CPP translated all our scripts to C++)

misty glade
#

not everything is in C++, only the unity libs are

#

mscorlib.dll, system.dll are still in the managed world

flint geyser
#

🤔

misty glade
#

hm actually maybe i'm wrong on that

#

this is from 2015

#

I’d like to point out one of the challenges that we did not take on with IL2CPP, and we could not be happier that we ignored it. We did not attempt to re-write the C# standard library with IL2CPP. When you build a Unity project which uses the IL2CPP scripting backend, all of the C# standard library code in mscorlib.dll, System.dll, etc. is the exact same code used for the Mono scripting backend.

#

but then there's the whole managed code stripping feature, which.. if i understand, implies that unity actually does crack the hood open on system.dll and mscorlib.dll and strip out managed chunks that aren't called/used to minimize the end build size

#

While this is no substitute for actual profiling and measurement, we can get some insight about the overhead of any given method invocation by looking at how the generated C++ code is used for different types of method calls. Specifically, it is clear that we want to avoid calls via run-time delegates and reflection, if at all possible.

#

interesting

#

I use runtime delegates allll the time

flint geyser
misty glade
#

I'm assuming the "VM" that runs IL - .net, in this case.. but I don't know (nor really need to know) how it works.. I just call functions, I'm a bad programmer 😉

severe grove
#

What is the preferred way to edit and store multiple paragraph long text? I am working on a narrative based game and trying to work with json in untenable because json does not support line breaks.

rocky mica
#

json does support linebreaks btw

buoyant vine
#

so does xml

severe grove
#

Is there a better window for editing strings in unity? When I click on it it keeps selecting it all and is a pain to work with.

rocky mica
#

using something external

#

I would honestly use a spreadsheet and make a script to import data from it

#

thats what I did for handling localizations for a game

#

scriptable objects with string dictionaries that could be imported/created from a xml/google sheets file

severe grove
rocky mica
#

just editing the cell

severe grove
#

Alright.

rocky mica
#

spreadhseet approach seems to be the most common from what I have seen

#

for localization at least

severe grove
#

is there a trick to resizing cells?

#

I guess I just have to buckle down and figure out how exel works.

rocky mica
#

we used google sheets, but in any program it's trivial to resize all cells

dark crow
#

does anyone familiar with Photon can you give me a overview differences between:

  • Realtime
  • Fusion
  • Quantum
sly grove
dim zephyr
#

How do I find the end coordinates of a rectangular GameObject?

drifting galleon
#

end coordinates?

forest cosmos
#

use collider bounds

#

get vertex position of the mesh

dim zephyr
#

Let me put it differently, I am trying to calculate what is the closest point of a barrier to my player. But I can't get it right.

            {
               Vector3 barrier = visibleObject.transform.position - visibleObject.transform.lossyScale;

               Vector3 direction = fov.transform.position - barrier;

               Handles.DrawLine(fov.transform.position, direction);
            }```
#

On the screenshot the green line represents where the point is right now (which is def not correct)

forest cosmos
#

do you need to calculate closest point to player in any direction or you're filtering to calculate distance from player to barriers only?

dim zephyr
#

I add to the list barrier(s) that is/are in the radius (white circle) in order to calculate closest point from player to the visible barrier(s)

#

I got a recommendation: You have to instead compute the distance and direction based on the closest point on the barrier. Since they are aligned with the x and z axes, this is quite simple – it’s just the difference in x and z value, respectively, for the two orientations of barriers.

But I still cannot figure out. So, the code is my poor try of implementing this recommendation

dim zephyr
#

So, I managed to get correct direction where the car should bounce (which is perfect), but still can't figure out how to draw a line to the closest point (by which I mean get that point)

            {
                float x = fov.transform.position.x - visibleObject.transform.position.x;
                float z = fov.transform.position.z - visibleObject.transform.position.z;

                Vector3 direction = fov.transform.position - new Vector3(x, 0f, z);

                Handles.DrawLine(fov.transform.position, new Vector3(x, 0f, z));
            }```
orchid marsh
dim zephyr
#

Yep, that was the question 🙂 How to determine it

orchid marsh
#

So you ought to break down your problem.. you need to find the closest point first.

#

Evaluate every object in your collection and determine which is closest.

dim zephyr
#

Actually no, I can figure out myself which one is the closest, what I am trying to implement is a bounce from a visible barrier.

So, when the player comes close to the barrier, I want to push him away from it, but I cannot figure out how to find the closest point of a barrier in order to calculate the direction.

orchid marsh
#

What does the barrier consist of? What is it?

#

Does it have a collider?

dim zephyr
#

It's a plane

orchid marsh
#

An origin? A radius?

#

So, send a raycast towards it from your player to determine the closest point.

dim zephyr
#

I understand what you mean, there is also Collider.ClosestPoint. But I am trying to figure out the math way as it is part of the assignment, but my math is not that good

orchid marsh
#

Under certain circumstances, the shortest path would be a raycast from your player in the normal of the plane.

#

(This wouldn't work if the plane is slanted - up direction is something other than up)

regal olive
#

I'm working on a voxel/cube character creator where after building your desired character you can combine the cubes together into one mesh, attach it to a skinned mesh renderer and preview animations on it. The cube prefab is the default cube model just with a custom material. Each cube is attached to one body part (Head, torso right hand etc.) and each body part has exactly one "bone" transform.
https://controlc.com/33bd5870
I'm getting a "bone weights don't match the bones" error. I don't see the reason for the disparity. When debugging the code I confirmed that the bones of the skinned mesh renderer are correctly assigned. All the expected bones, in the expected order.

#

Rig and the body parts for visual reference. Rig visualized by Animation Rigging package

meager kite
#

How would i obfuscate JSON data? Right now all my save data is very easily readable and changable

austere jewel
#

Sounds good

buoyant vine
#

to obfuscate them is senseless... just serialize them as byte code / machine code wahtev er its called

#

if someone wants to read it ... he will be able to do so

#

you can just make it harder

meager kite
#

Hm alright

buoyant vine
#

if this is for "security" thats just stupid ( dont feel insulted )

#

obfuscation doenst increase security

meager kite
#

Really? How do i stop people from tampering with this stuff then, excluding things like cheat engine

buoyant vine
#

if you want security you have 2 choices.. either Easy anti cheat protection ( client side check if ... not that useful at all ) or server side

#

server side is the most protective way of securing your game

devout hare
#

Why would you care? If someone wants to tamper with their own game, just let them

#

If it's multiplayer then you shouldn't be saving data on the player's computer anyway

buoyant vine
#

basically it says... "single source of truth" , if a user sends malformed data to the server the server just declines and says " fuck off with that " and you kick him

#

thats the highest protection you can make... you check every user request

meager kite
#

Alright thanks for explaining it

buoyant vine
#

none can change the code of your server

#

so you know that that one is always unchanged

#

you will never know what the client will do

#

decompiled and deobfuscated is done in an hour

#

thats no protection

#

its just for annoyance

misty glade
#

to be fair, you eliminate a huge part of the cheating with messages that are serialized to byte[] imho

#

if your data comes over the net in plaintext json .. well, you're pretty much giving away exactly how to modify and tinker with it

obsidian glade
# devout hare Why would you care? If someone wants to tamper with their own game, just let the...

path of least resistance - people playing games will follow that even if it means spoiling their own fun. If x mechanic is especially good/rewarding, even if it's less fun, people will do it and then complain that your game sucks. If you have completely transparent and editable save data to the point it's trivially easy to understand and do, people will spoil their own fun by doing it. If you obfuscate it, even just a bit, it can maintain the illusion that playing the game as intended is the path of least resistance and lets them enjoy it as it's meant to be played

unkempt socket
#

Hey!
So I found parts of this code in the internet and am not really understanding it... Any CS and math pros in here who could try to explain what heppens for this 3d cam controller?

#
    void LateUpdate()
    {
        float scrollData = Input.GetAxis("Mouse ScrollWheel");

        targetZoom -= scrollData * zoomMultiplier;
        targetZoom = Mathf.Clamp(targetZoom, 4.5f, 30f);
        cam.orthographicSize = Mathf.Lerp(cam.orthographicSize, targetZoom, Time.deltaTime * 10);
    
        currentX += Input.GetAxis("Mouse X") * sensivity * Time.deltaTime;
        currentY += Input.GetAxis("Mouse Y") * sensivity * Time.deltaTime;
 
        currentY = Mathf.Clamp(currentY, YMin, YMax);
 
        Vector3 Direction = new Vector3(0, 0, -cam.orthographicSize);
        Quaternion rotation = Quaternion.Euler(currentY, currentX, 0);
        transform.position = lookAt.position + rotation * Direction * -1;
 
        transform.LookAt(lookAt.position + new Vector3(0, 3, 0));
    }
lavish lotus
#

doesn't the tutorial or whatever explain this...?

unkempt socket
#

D:

sly grove
unkempt socket
sly grove
#

I don't see any reason why that needs to be there

#

it should just be Vector3 Direction = Vector3.back;

unkempt socket
#

also can you explain what a Quaternion (and also why I´m using the Quaternion.Euler) is? Also no worries, I´m currently googling myself, but mayb you have a better explanation! 😄

sly grove
#

A quaternion is just a variable that represents a rotation

#

that's all you need to really know

#

Quaternion rotation = Quaternion.Euler(currentY, currentX, 0); establishes a rotation variable with currentY degrees around the x axis and currentX degrees around the y axis

#

This part is just saying "put the camera at the target's position + that back vector, rotated by that rotation:
lookAt.position + rotation * Direction * -1;

unkempt socket
sly grove
#

it should just be Vector3.back * some constant

#

but they basically have Vector3.back * orthSize

#

which is pointless, because an orthographic camera doesn't zoom by moving closer/farther from the target.

Honestly my guess is that whoever wrote this adapted it from code that used a perspective camera

#

and you might be Vector3.back * zoomDistance there in that case

#

as that would actually make sense for a perspective camera.
You'd put the camera closer/further from the target to zoom

unkempt socket
#
       targetZoom = Mathf.Clamp(targetZoom, 4.5f, 30f);
        cam.orthographicSize = Mathf.Lerp(cam.orthographicSize, targetZoom, Time.deltaTime * 10);
```even tho i clamped the value
unkempt socket
#

any idea tho, why I can´t look further down than this?

sly grove
#

you'd need to change YMin and YMax to adjust the maximum tilt angle

unkempt socket
#

ooooh yeah

#

that makes sense

#

mb

unkempt socket
unkempt socket
#
            float targetAngle = Mathf.Atan2(movementX, movementY) * Mathf.Rad2Deg + cam.eulerAngles;
            Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
            rb.AddForce(moveDir.normalized * speed);
#

so this variable is kinda weird, bc it always return 57.smth, but without it, my player would always move in the direction in which my cam is looking, no matter the input - at any input for the movement

dusky remnant
#

Hi, i opened my project just now and it compliled with lots of errors. It was fine yesterday when i closed it, but now its messed up. the errors are shown in the image. Anyone know how to fix this?
i have never touched the scripts causing the errors

sly grove
dusky remnant
sly grove
#

all the errors are from it

unkempt socket
#

think it was from a youtube video

dusky remnant
barren nacelle
#

is there a way to use Matrix4x4 * Vector4 without removing the w coordinate from the vector?

obsidian glade
unkempt socket
#

looks way cleaner now

spring oyster
#

There's any way to deserialize XML files to C# classes without manually looping all the XML nodes?
Something like the way we deserialize JSONs?

formal lichen
#

haha I haven't done that with XML, although it can be more granular. I'd assume you could using the same technique JSON does with custom Attributes

spring oyster
honest hull
#

How do I set a temporary render texture to randomreadwrite enabled if I cant set that property after its gotten?

undone coral
#

and you have to change this setting

#

you want to keep the same C# reference, but create a new render texture?

#

which is routine and possible

#

i'm not sure about this specific property, it surely can be set by the constructor right?

#

in unity, the C# object called RenderTexture also holds a native pointer (get native texture pointer)

honest hull
#

I use this to create a temporary render texure of a given size I need for this iteration:

RenderTexture.GetTemporary(TargetWidth, TargetHeight, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear);

if I try to sset it to readwriteenabled it yells at me that I cant do that to an already created rendertexture, but only if I use releasetemporary instead of release to dispose of it

undone coral
#

create and dispose / destroy work on that pointer

#

yeah

#

the native object that the RenderTexture class manages, which is a graphics device specific thing, is indeed immutable

#

what's wrong with using release temporary?

honest hull
#

it yells this at me

#

where this is what its yelling at me for

        for(int i = 0; i < 5; i++) {
        TargetWidth *= 2;
        TargetHeight *= 2;    
        TempTex = RenderTexture.GetTemporary(TargetWidth, TargetHeight, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear);
        TempTex.enableRandomWrite = true;
        RenderTexture.ReleaseTemporary(TempTex);
        }
undone coral
#

are you confident you can't enable random write in the constructor?

honest hull
#

these are the ways to create it

undone coral
#

if not, you have to do

        TempTex = RenderTexture.GetTemporary(TargetWidth, TargetHeight, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear);
        RenderTexture.ReleaseTemporary(TempTex);
        TempTex.enableRandomWrite = true;
        RenderTexture.Create /*or whatever it is, temporary*/
#

well there it is

#

rendertexturereadwrite

sly grove
#

ReadWrite is always enabled by default when you create a texture in memory, at leeast I thought so

undone coral
#

use the named args

#

since they're optional

honest hull
#

readwrite is only for linear vs nonlinear color

undone coral
#

you got this

honest hull
sly grove
undone coral
#

why are you setting this flag then

honest hull
#

but I need to write to it in a compute shader

undone coral
#

i see

honest hull
#

so unity wouldnt yell at me

undone coral
#

well try the snippet i shared

#

unity might have a bug

sly grove
#

I think you can always write to it in a compute shader. The isReadable flag is about whether there's a CPU-side copy of the texture available or not

honest hull
#

this was all to get around the unity object ID being out of range after awhile D:

honest hull
#

wait sorry its enableRandomWrite not readwrite

nimble lynx
#

Hey, has anyone tried rendering a USD stage in Unity. I am curious if can use USD's Python or C++ API in Unity to manipulate the USD stage.

undone coral
#

USD files have all plain materials with a preview texture

#

you probably haven't discovered what usd's purpose is

nimble lynx
#

I have a USD stage for a simulation and I want to render it in Unity without converting it to Unity GameObjects

undone coral
#

what do you mean by stage?

#

are you trying to say a USD file

#

what is it really?

#

for a simulation of what? are you trying to say like a robotics / scientific / non gameplay simulation?

#

when you say use USD's API to manipulate the "stage," what do you mean?

#

USD is meant for multiple editing systems to add their own dedicated layers

#

and to provide some sort of preview / compatibility of those other layers

nimble lynx
#

Ok, so a USD file can be composed of a bunch of other USD files using USD's composition Arc. The final output of the composition is the resultant stage in USD which consists of USD prims.

undone coral
#

Unity doesn't know how to interpret layers from other tools in a special way. it only uses their preview features, which is the standard

#

so you'll see geometry with materials that have a preview texture

nimble lynx
#

Does unity convert the USD to Unity gameobjects to render them?

undone coral
#

so what do you mean by that

#

everything that can be dragged and dropped into the scene is a game object

#

do you mean does it represent the hierarchy preview as a hierarchy of game objects? i think it does, but i think it's also controllable with a check box in the importer

#

it "converts" it in the same way it "converts" an FBX to a prefab

#

the represented hierarchy is linked to the file