#archived-code-advanced

1 messages · Page 179 of 1

drifting galleon
#

you won't even notice a performance hit with sqrt

woven marsh
drifting galleon
fathom locust
#

If anyone here has worked with FMOD before - I know that FMOD is generally designed to react to gameplay via parameters. But is there any way to do things in reverse; to allow code to respond to triggers within FMOD events?

For example, allowing a looping music section to finish before triggering a gameplay section.

gray pulsar
fathom locust
#

Awesome, I'll look into them!

soft hawk
#

So training neural networks is not so easy lol

#

But I have found a few bugs and squashed em

royal forge
#

Hi folks...Is there a way to manage a window within unity, but outside of the main unity build window?

#

like if I wanted to drag game components outside of the main build window

#

i.e. a single game or app that can use multiple windows

regal olive
#

I need some help calculating the rotation of my AI to activate a turn animation in a blend tree, I need to calculate the left turn to -1f, and the right turn to 1f. is there anyway I could do this?

undone coral
royal forge
undone coral
#

is this only for windows?

#

what's the objective?

royal forge
#

The objective is to have multiple components that can be dragged outside of the main view space....so I can have the main game screen on one display, and helper components dragged off to other displays in windows.

regal olive
# undone coral ?

I need to calculate the the angular velocity of a game object and convert them to a right and left float (-1f, 1f)

#

So if the game object turns right I will get a float of 1

#

And if it turns left I will get a float of negative 1

plucky laurel
compact ingot
royal forge
plucky laurel
#

theres an asset "full screen editor" they are doing os level hacking to render into a window

warm adder
#

Hya. I'm running into some Vector math issues. I'm using Shadergraph, which leaves me without the usual way I'd do stuff (Quat.LookRotation etc) . I got two transforms, and I need to rotate transform A so its looking to transform B. Because I'm using shadergraph I need to calculate it "Raw"

#

I can calculate heading and direction easily. But I'm running into trouble to convert those to EulerAngles or Radians

#

which is what I need to rotate the object

#

So, the question: without using Quaternion functions and the like, how does one calculate the rotation degrees or radians a transform from a direction or heading vector3?

sly grove
#

Quaternion.LookDirection makes a quaternion pointing in your heading direction. Then you can just Quaternion.RotateTowards or Sleep to rotate it

warm adder
#

I;m using Rotate About Axis nodes (working on a billboard shader)

sly grove
#

Oh shaders?

warm adder
#

Yeah shadergraph. So I need to manually convert a directional Vec3 to a rotational Vec3

sly grove
warm adder
#

I've tried for a few days there, channel is kinda slow / dead 🙂

#

and since it's kind of "basic" Vector math, I though I'd ask here

#

and, unfortunately my Google Fu is letting me down / alsways redirects me to Quat.LookRotation and Vec3.RotateTowards

mild yew
warm adder
#

thanks! looking into it now

mild yew
#

Also instead of Rotate About Axis - just multiply the quaternion with ur position to rotate

warm adder
#

not sure if that is possible. But I kinda like the Rotate About Axis (tree billboard shader, so X/Z always 0), saves maniuplation beforehand

mild yew
#

could just 0 out the unwanted axis 🤷‍♂️

warm adder
#

So, to get radians / degrees, I need to construct a quaternion. I'll still need to convert from the quat to radians then, looking up that formula now

mild yew
#

or, you know - you could just multiply the position instead of doing that weird conversion to get rotatet around axis working (which is just a worse way of multiplying a quaternion)

#

🤔

regal olive
warm adder
# mild yew <@!579057039267856385> my first google result https://stackoverflow.com/question...

I'm trying it out in code first, to wrap my head around it etc.. https://pastebin.com/qYTvfCrW I'm getting 0,0,0 for the cross product though, the Quat is always empty too. You see what I am doing wrong?

compact ingot
#

I suppose what you want to use for the cross product is transform.forward instead of transform.rotation.eulerAngles

warm adder
#

Ah yeah. of course. Thanks!

rapid lotus
#

is there a way for me to generate .meta files "outside of unity"? i've been trying to apply URP's FSR patch, but unity doesn't find .meta files and does not generate them because the folder is immutable.
all the new FSR-related files that have been added have show this kind of error, and the files are as if they weren't there, indeed because no meta files were generated.

Asset Packages/com.unity.render-pipelines.universal/Shaders/PostProcessing/amd_fsr.hlsl has no meta file, but it's in an immutable folder. The asset will be ignored.
warm adder
#

I'm pretty sure I can use all those functions in shadergraph too. So if I get this to work I can recreate it there

misty glade
#

Was curious as to the performance of setting a TMPro.text member on every frame (hard to profile/test this use case, thought I'd look at the code first). The setter is:

    /// <summary>
    /// Base class which contains common properties and functions shared between the TextMeshPro and TextMeshProUGUI component.
    /// </summary>
    public abstract class TMP_Text : MaskableGraphic
    {
        /// <summary>
        /// A string containing the text to be displayed.
        /// </summary>
        public virtual string text
        {
            get { ... }
            set
            {
                if (m_IsTextBackingStringDirty == false && m_text != null && value != null && m_text.Length == value.Length && m_text == value)
                    return;

                m_IsTextBackingStringDirty = false;
                m_text = value;
                m_inputSource = TextInputSources.TextString;
                m_havePropertiesChanged = true;
                SetVerticesDirty();
                SetLayoutDirty();
            }
        }

Am I right in understanding that as long as the text is the same from frame to frame (m_text==value) that none of the expensive redraw happens?

#

Or do I need to dig deeper into subclasses of TMP_Text

flint sage
#

Yes you're right

compact ingot
ancient talon
#

Sorry for the late respond - was trying to mimic texture alias by combining multiple texture together (customizations), so that I don't have to render more than 15 unique overlay texture at the same time.

tawdry wraith
#

How do you make a character move? I use 2020.3.18

tranquil dove
#

how do i do this? the red orb is the player, which shoots a projectile by instantiating a bullet and adding a transform.right force. then, i want it to bounce on that blue orb like the trajectory i drew with my distinct drawing skills

#

(i want the bullet to "bounce" off the orb in that way)

#

i've tried using bullet.addrelativeforce, but it doesn't give the effect i want.

devout hare
#

It's not clear how you want it to behave

#

should it always change the velocity 90 degrees to the right?

stiff spear
#

Vector3.Reflect on collision and use the result as the new trajectory

tranquil dove
tranquil dove
devout hare
tranquil dove
#

i just have to understand how reflect works first haha

stiff spear
#

it sounds like he just wants it to ricocet on collision

#

which is what reflect should do

tranquil dove
#

@stiff spear @devout hare and how do i get the inDirection? i'm applying a force to move the bullet (from the gun barrel), i don't think RB.velocity would work(?)

stiff spear
#

when i did it, i wrote my own physics and just moved the transform every frame

#

i can try to pull up the code

tranquil dove
#

nah no problem ahah

#

i mean

stiff spear
#

i mean its a bullet right? all you really need is a raycast at the front of the object

#

no need for rb

tranquil dove
#

well, i use it to apply rb.addforce

#

but i could also use rb.velocity

#

by the way, if you want, that would be great

stiff spear
#

this is what i did

#

in update loop

#

on bullet object

#

you can ignore the component stuff

#

hit point is just a empty game object at the front of the bullet

#

so i can position the raycast correctly

tranquil dove
#

stupid question: this is a bullet based shooting mechanic or a ray based?

stiff spear
#

the initial angle is just your bullet spawn point forward vector

devout hare
#

Velocity is the direction the object is moving, by definition

stiff spear
#

its less expensive than a rigidbody

#

which may not matter in your case

stiff spear
tranquil dove
#

just another question: what is that network destructible component?

stiff spear
tranquil dove
#

okay

#

i'm gonna try to implement it and see how it goes. Thanks a lot, you saved me lol

stiff spear
#

np, all you really need is the vector3 reflect on collision and replace the current movement vector with the newly reflected one

#

and make sure to reflect it against the hit points normal, idk if a normal rigidbody collision will give you that but yea

tranquil dove
stiff spear
#

Very epic

upper hinge
#

Does anyone here use a particular commit or versioning convention for their end-user Unity projects (as opposed to libraries or assets)? I'm trying to clean up my project and my development process, and I figure adopting a commit convention would help.

undone coral
undone coral
misty glade
misty glade
#

i couldn't find the code for the UGUI child class, but assumed "no" based on the check in the parent

#

it's probably OK - i'm only thinking ~100 text objects for ~1 second, so .. even if the redraw-ed, it probably wouldn't be worth testing/profiling

undone coral
#

if nothing else changes* it will not cause the component to recalculate the text rendering

#

but lots things cause transforms in UGUI to change which trigger a redraw

misty glade
#

(they don't otherwise change for that 1 second)

upper hinge
misty glade
# upper hinge Okay, but what about versioning and commits before then? (Assume that I will be ...

I tend to use a modified gitflow strategy - I simply check into master and commit with "WIP" as I go, and then squash those commits (and remove all the "WIP" messages) when an actual stable milestone is reached, and tag that release (so I can go back to it easily).

I was doing full gitflow for a little while (ie, branching off of "develop", naming the branch after a feature, then merging it back) but it was more hassle/paperwork than I needed, and also I tend to "mostly" stay on target for a feature, but there's a lot of cleanup and ancillary work as I go, and I didn't like mentally "asking my manager if I could do that work"

undone coral
#

treat testflight and google play beta releases as releases

#

they get tagged

#

there's an audience for ad-hoc distributed game builds, and it's a bad one*

#

beta testers, publishers, localization people - you will give them a non-latest build, they receive a polished / limited build, so it goes

#

you give them "master," and you've just made them nonprofessional QA testers

frank peak
#

makes sense

#

your explanations are always v thorough, much appreciated lol

undone coral
#

lol

frank peak
#

idk personally im leaning towards a steam beta test when at that stage, but yeah releasing the latest build doesn't make sense at all

#

cuz you can do override keys (ie personally hand out beta steam keys on the discord) and as long as your under a few thousand keys its all good

#

but itll be a hassle to keep track of

undone coral
#

the automation process was a hassle but it worked fo rme

#

i wish you could release a steam build without touching the website

#

so it goes

frank peak
#

lmao fair

#

i haven't delved much into steam works yet

#

i watched the vid on uploading a build

#

but thats it

undone coral
#

steamguard-cli is an important ingredient in the automation toolkit

frank peak
#

ah yeah eh

#

i gotta learn it eventually

undone coral
#

one interpretation of the lack of automation in steam, the app store, google play is that successful apps rarely need daily binary update support

#

your client should be thinner, essentially

frank peak
#

hmm i see

undone coral
#

the best games on apple app store nowadays are apple arcade, and those get released once, updated twice, then done

#

why do automation

frank peak
#

so fair

undone coral
#

we'd have to ask the steamdb guy how often steam game binaries are updated

frank peak
#

itd be hype to hit on a valheim-type success but thats like the lottery basically lmao

undone coral
#

would be an interesting study question

frank peak
#

ye true

#

i wonder if they have any stats on stuff like that as is

#

ah i guess not -- quick google turns up nothing on steam work stats

undone coral
#

valheim is rarely updated anyhow

#

much more so in february march of last year than now

#

but even then, at most 3 builds a week... might as well upload yourself

frank peak
#

dang eh

#

idk i like the idea of steam because of how popular it is

undone coral
#

it's gucc

frank peak
#

20-30 million DAUs using the last few days as a point of reference

undone coral
#

comparing this game, which was indeed upgraded frequently, to a website

#

like a website with that number of DAU probably gets updated 3x a day or more

frank peak
#

jeez eh

undone coral
#

so personally i push back against the frequent update mindset

#

it is adverse selection

#

even at the highest scale

frank peak
#

yeah fair

undone coral
#

if you are doing something in software that needs to be updated 3x a day, which could be really cool, how can you make tha ta website?

frank peak
#

i keep frequent backups but thats just cuz my computer was really unstable (black screen issues) until i reseated the graphics card

undone coral
#

as opposed to - how can i update a steam game 3x a day

frank peak
#

but im talking a backup every three to five days

#

which isn't too frequent tbh

#

if i uploaded to steam itd probably be months between builds

#

unless it was bug fixing after a build

#

then itd probably be as soon as the bug as solved or w/e and the build was stable

undone coral
#

yeah

#

how often do non-professionals give actionable bug reports?

frank peak
#

good question lol

#

hard to say

#

im gonna have to develop a core group of beta testers

#

that i refer to and trust

#

but keep it smallish and try to get a range of hardware to see how the game perfoms

#

id say tho for the most part your beta testers might just be chance at a poor review in an early state

#

esp if its really public ie steam play test

#

but idk

#

its hard to say without having been thru it

tender badger
#

How would one make a pathfinding AI that can navigate an arbitrary 2D collider shape, and is performant up to, let's say, 50 instances of it running at the same time. I don't need AI in my game yet, but I'd like to be ready for the future, and if possible, try to program the other parts of the game to be ready for that if necessary.

frank peak
#

you could just use an out of the box solution like the a* pathfinding project, theres a free version for 2d

tender badger
#

What's the license for that if I want to publish my game at some point?

frank peak
#

im not sure but it says on the page lemme get the link

tender badger
#

That said, my 2D space is not a grid, there's triangular and circular shapes as well.

frank peak
shadow seal
#

If you make the grid small enough, it will look good enough

tender badger
#

I suppose what I could do is somehow hardcode specified paths that the AI will follow.

#

It would only be a last resort though, as that's an ugly solution, and for the bigger space ships I'm planning it sounds like a pain to do all of them.

frank peak
#

writing your own pathfinding code isn't too tricky if you want it to be grid based lol but yeah idk otherwise how you'd do it

tender badger
#

(Basically, I want AI crewmembers to automatically go to damaged components of the ship during combat like the reactor and repair them.)

frank peak
#

i see

tender badger
#

How about writing the pathfinding for impostors that can sabotage your components?

frank peak
#

i dont think it'd be too hard either

#

the pathfinding code you can reuse

#

writing the ai code is a little trickier

#

i used that tutorial i linked above for pathfinding

#

and then the ai which controls the behaviour

#

its v thorough and indepth

#

its one method thats easy to implement, flexible, and it is contrasted vs behaviour trees and finite state machines

#

tho later on the tutorial implements a finite state machine to act as controller, basically to transtition between three states -- move, execute and decide

#

I haven't hooked up the utility AI to the pathfinding yet

#

but this is what it looks like (blue line is a drawn gizmo, green and red dots are drawn primitives that incidentally murder the frame rate lol)

#

took me maybe 10 days total to code ngl

#

but im kind of a newb

remote gyro
#

I have a bash script that should auto push my Unity Cloud iOS builds to appstoreconnect. I use the same bash script on every project, but for some reason on this project I'm getting errors. Can someone take a look at this error and see if you can figure out what I'm doing wrong?

granite viper
#

👍

#

these are the best kind of problems to have because they mean the sky isn't falling 😄

remote gyro
#

I was looking in wrong project. indeed the scripts are where they should be. I wonder if my git is ignoring them

granite viper
#

some of the default gitignores do ignore sh iirc

remote gyro
#

just check my repo. its up there on github

#

so, not sure whats going on

granite viper
#

spooky

remote gyro
#

might have something to do with my org ID or my app name because of line 3 of the bash i'm using

echo "Uploading IPA to Appstore Connect..."
#Path is "/BUILD_PATH/<ORG_ID>.<PROJECT_ID>.<BUILD_TARGET_ID>/.build/last/<BUILD_TARGET_ID>/build.ipa"
path="${UNITY_PLAYER_PATH}"
if xcrun altool --upload-app --type ios -f $path -u $ITUNES_USERNAME -p $ITUNES_PASSWORD ; then
    echo "Upload IPA to Appstore Connect finished with success"
else
    echo "Upload IPA to Appstore Connect failed"
fi```
#

not sure if it gets org_ID and Project_ID from unity dashboard, or if it gets it from my project settings

granite viper
#

what does echoing those get you?

remote gyro
#

another weird thing though, is the build shoudl have failed if this script failed, but for some reason, its not telling cloud build that it failed. oh well. at least i was able to look at the console. i have to run to get groceries, then maybe i'll figure this out

granite viper
#

gl

remote gyro
#

oh that build path is my github directory

remote gyro
#

one of my environment variables keeps getting deleted (this time its my itunes password). I've added it back. hopefully this solves it.

quiet pasture
#

I was hoping someone could help me figuring out how to create a player movement script that allows the player to move through the WASD keys, through clicking to move, and through click and dragging. Basically I want to fit all these three movement features in a 3D project without them cancelling each other out. Thanks in advance

urban warren
quiet pasture
granite viper
#

that's something you need to decide

#

what happens if you start using WASD when in the middle of a click to move?

#

which has priority

urban warren
#

Or you could have like an int which is the current movement methods priority which is set when input happens, that way only the one with the highest priority happens.

urban warren
#

Question: How do you add a handler to an eventInfo whose delegate takes an internal type parameter (specifically an enum)?

wispy epoch
#

Hi I've been using Playfab for most player account data up to this point. I know Playfab has an inventory system available but from what I've read, it seems like you can't edit the stats of your inventory items with it. I want to create a system where once the player buys a weapon from the shop, they can purchase upgrades for it to increase its stats. What is the best way to accomplish this with safe data that stays bound to the account (not just the device and could be lost if uninstalled, so playerprefs i think would be a bad idea). Maybe im misunderstanding playfab's capabilities? Or is there a better way. Thanks

quartz stratus
jovial totem
#

Can the profiler do a call stack, or break a function down into its smaller parts? I know my update function is taking 150 ms but I dont know which part of it

novel wing
granite viper
#

you can also turn on deep profiling

jovial totem
#

Wit hthat ive figured out the problem but not how to fix it

#

I'm calling Twexture2D.GetPixel whatever 257^2 is like 5 times in a single frame.
Is there a more efficient way to do this:

//Tex is a Texture2D
float[,] heights = new float[257, 257];
            using (s_ProcessHeights.Auto())
            {
                //convert data
                for (int x = 0; x < 257; x++)
                {
                    for (int y = 0; y < 257; y++)
                    {
                        //tex.GetPixel(y, x).r;
                        s_GetPixel.Begin();
                        heights[x, y] = tex.GetPixel(257 - y, 257 - x).r; //this is just me fiddling until i got it to work right
                        s_GetPixel.End();
                    }
                }
            }

I can move the 257-x and the coordinates swapping to the script that generates the images so no math needs to be done

#

Is there a way I could like, dump the contents of the PNG to a 2D array like this?

#

I could also have it be a 2D array of Color32s and just use the r value later but that seems like a waste of ram

#

Or... could I make a compute shader to do this? This seems like a good multithreaded process

#

or use C# jobs

novel wing
#

Depends on what you're doing with each pixel? ComputeShader is prob the champ here though

undone coral
#

calculate the stats by summing the base and upgrade items' effects

undone coral
#

wouldn't an event with greater visibility than its types be a compile error?

#

it is in java

undone coral
jovial totem
wispy epoch
jovial totem
wispy epoch
#

I'm using a URP shader graph in my game that creates an ammunition bar that shows the bullets left in the mag and one dissapears each shot. Works well. I'm trying to use the same exact shader graph in my armory scene however, and the image shows up fine in both scene and game view but not once i play it. So it must be an issue with rendering. Worth noting that the ammo bar was in world space and this is on the UI layer so that could be part of the problem.

Open to other options that would be easier than updating the fill amount of this shader graph for each weapon stat. Im sure i could just have each bar representing a stat level be its own game object that can change sprite/color individually but i feel like having 40 game objects for something like this is bad practice.

mild yew
#

hey, does anyone have the formula to calculate the timestrecht when changing the pitch of an audioSource?

#

I thought it was Pow(pitch,2) but am not sure :/

normal moth
#
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;

public class NetworkManager : MonoBehaviourPunCallbacks
{
    // Start is called before the first frame update
    void Start()
    {
        Connect();
    }


    public void Connect()
    {
        PhotonNetwork.ConnectUsingSettings();
    }


    public void Play()
    {
        PhotonNetwork.JoinRandomRoom();
    }

    public override void OnJoinRandomFailed(short returnCode, string message)
    {
        Debug.Log("Tried to join a room and failed");
        PhotonNetwork.CreateRoom(null, new RoomOptions { MaxPlayers = 4 });
    }

    public override void OnJoinedRoom()
    {
        Debug.Log("Joined a room - yay!");
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

JoinRandomRoom failed. Client is on NameServer (must be Master Server for matchmaking) but not ready for operations getting this error

safe whale
half urchin
#

Hi are someone know how to make a top down world generator?

urban warren
spare pond
#

Are there any people using Unitask?

I can't find out how to check if the task is running. I want to make some kind of spawner with an interval timer. I want to prevent the method from being executed again. Ended up using bool flag variable but this does not satisfy me

noble stream
spare pond
#

@noble stream Yea I tried but im beginner with this framework and async aswell (trying out before diving into theory hole).
I want something like this

private void Start()
{
  StartSpawn();
  StartSpawn(); //should be ignored or give exception
}


private async void StartSpawn()
{
    if (started) return; // or write exception
    
    await SpawnInterval(.5f);
}

private async UniTask<bool> SpawnInterval(float seconds)
{
  while (!IsFull())
  {
      await UniTask.Delay(TimeSpan.FromSeconds(seconds));
      Spawn();
      started = false // or something like that
  }

  return true ; //or started = true;
}
#

Feels like that Im thinking wrong about how i can work with that

trim ember
#

I am having a problem with Rpc's and Generics. I am getting a compile time error with my code:

public class NetworkHandler<T> : NetworkBehaviour where T : unmanaged
{
    private NetworkVariable<T> _networkVariable = new NetworkVariable<T>();
    public void InitGeneric(T value)
    {
        Debug.Log("Testing Generic Method");
    }

    public void SetValue(T value)
    {
        if(!IsOwner) return;

        if (NetworkManager.Singleton.IsServer)
        {
            _networkVariable.Value = value;
        }
        else
        {
            SubmitPositionRequestServerRpc(value);
        }
    }
    
    [ServerRpc]
    void SubmitPositionRequestServerRpc(T value)
    {
        //TODO implement Rpc logic
    }
}

and the implementation would be like this:

public class NetworkTest : NetworkHandler<int>
{
    private Random _random;
    private void Start()
    {
        _random = new Random();
        Debug.Log("Testing Less Generic Method");
        InitGeneric(10);
    }

    private void Update()
    {
        //Post a random value and sync over network
        if (Input.GetKeyDown(KeyCode.Space))
        {
            SetValue(_random.Next(1, 20));
        }
    }
}
#

This is the error (Too long for discord to handle so its a screen shot). I am using the Netcode for gameobjects package

Because with my implementation the generic would be hard typed on compile time (because of the interface inheritance) I dont get why it is giving errors, Any thoughts?

deep blaze
#

Assets\Script\CarController.cs(42,71): error CS1011: Empty character literal

shadow seal
trim ember
deep blaze
#

i dont even now what that is

shadow seal
#

That would be an empty char literal

deep blaze
#

thx

trim ember
#

char a = '\0' would work

deep blaze
#

doesnt work

spare pond
#

UniTask Completion issue

shadow seal
deep blaze
#

how do i do that

shadow seal
deep blaze
#
using System.Collections.Generic;
using UnityEngine;

public class CarController : MonoBehaviour
{
    //wheel colliders
    public WheelCollider wheelFL;
    public WheelCollider wheelFR;
    public WheelCollider wheelBL;
    public WheelCollider wheelBR;

    //torque colliders
    public float engineTorque;
    public float brakeTorque;

    //steering angle
    public float maxSteeringAngle;

    // Start is called before the first frame update
    void Start()
     {

     }

    // Update is called once per frame

    void Update()
    {
        if(Input.GetAxis(''Vertical'') > 0)
        {
           wheelFL.motorTorque = engineTorque * Input.GetAxis(''Vertical'');
           wheelFR.motorTorque = engineTorque * Input.GetAxis(''Vertical'');
           wheelBL.motorTorque = engineTorque * Input.GetAxis(''Vertical'');
           wheelBR.motorTorque = engineTorque * Input.GetAxis(''Vertical'');
        }
        if(Input.GetAxis(''Vertical'') < 0)
        {
           wheelFL.motorTorque = brakeTorque * Input.GetAxis(''Vertical'');
           heelFR.motorTorque = brakeTorque * Input.GetAxis(''Vertical'');
           wheelBL.motorTorque = brakeTorque * Input.GetAxis(''Vertical'');
           wheelBR.motorTorque = brakeTorque * Input.GetAxis(''Vertical'');
        }
    }
}        
char a = '\0';
shadow seal
#

Why on earth would you do that

#

All those Verticals must be in " "

deep blaze
#

vid on yt i tried to make a driving car

shadow seal
#

You didn't follow it very well then

#

And that char a at the end was an example to you, not something for you to copy

trim ember
deep blaze
#

idk

hollow garden
#

my brother in christ it's " not ''

#

that's all

trim ember
#
if(Input.GetAxis(''Vertical'') > 0)
//shoud be 
if(Input.GetAxis("Vertical") > 0)
hollow garden
#

yes

shadow seal
hollow garden
#

wait we are

#

🤨

trim ember
deep blaze
#

its fixed

#

thx you

trim ember
#

@deep blaze there is a chat thread for code-beginner these question should probably asked there

deep blaze
#

oke

jovial totem
#

Okay so. If I wanted to set a heightmap from script it would have to say be 257x257 right? And does setheights start from 0,0 or 1,1? Logic says 0,0 but I have a 257x 2D array and it still is off by 1 somewhere giving me this weird gutter

sly grove
#

And wdym by "SetHeights"? Are you talking about Terrain or something?

jovial totem
#

Oh I thought it had to be a power of 2 + 1

jovial totem
sly grove
#

oh - maybe start with that context 😵‍💫

#

and no, it's zero based, of course

#

it's an array

#

You're right about power of two plus 1

#

so yes 257x257 makes sense

undone coral
#

you do not need a networkvariable or networkbehaviour

#

declare the typed variable where you need it

#

unity's "codeweaving" (IL bytecode instrumentation) is throwing the exception you see

#

i cannot tell what value your generic code is providing but it is not worth banging your head agsint for little value

trim ember
#

I posted it on the github page of netcode for gameobjects as an issue and will move on for now. because you are right that it is just a little detail and not a big problem

undone coral
#

that's the spirit

#

it's baffling unity still has a codeweaving based approach to this

#

instrumenting IL code, unlike java bytecode, is a huge pain in the ass

undone coral
#

if it's an enum, try redeclaring it in your own code

#

and see what happens

urban warren
undone coral
#

runtime errors right?

urban warren
#

Yeah

undone coral
#

you can use the information in the exception to construct the right type

#

which will be a subclass of Enum or whatever

#

then use the general int to enum methods to construct an instance of that type or whatever

#

but i don't know why that would matter since aren't enums erased in c#? no idea

urban warren
#

I tried using Enum, but it returns null :/

undone coral
#

okay so help me understand

#

you can retrieve this internal event correctly

#

but not a type in one of its delegates parameters? why?

#

also what assembly is it?

#

like what's the goal

urban warren
#
// In Unity assembly
internal enum HierarchyChangeType { Add, Remove, Move }

internal static Action<VisualElement, HierarchyChangeType> hierarchyChanged;

I want to get the hierarchyChanged event and add a callback to it so I can run some code when the event is raised.

urban warren
undone coral
#

hmmm

#

but in react you do not have to do this

#

so why do you have to do this in UIElements

#

anywya, if you really need this

#

the source of UI toolkit is open

#

you can (1) redeclare these

#

(2) create an assembly info that marks your assembly as a friend

#

InternalsVisibleTo

#

if you didn't want to modify their code at all

#

create an assembly info with the name DynamicProxyGenAssembly2

#

and it will be able to access the internal types @urban warren

#

does that make sense?

#

you will never have the dynamicproxygenassembly2 in your project, which is why i chose it

#

so you'd have a directory with asmdef DynamicProxyGenAssembly2

#

and it references com.unity.ui

urban warren
# undone coral so why do you have to do this in UIElements

Because I am working on a split view and was wanting to be able to register callbacks with the panes when they are added/removed.

While I could do what you suggest, it feels overkill. I am like 90% sure there is a way to do it with just reflection.

undone coral
#

no

#

reflection in C# is not powerful

#

both of these methods are superior to reflection anyway

#

because they both use the real approaches - one is making the source what you want, and the other is to respect the internal declaration

#

sort of 🙂

#

you can use the DynamicProxyGenAssembly2 to only provide the bridge you need to this internal type

undone coral
#

i do not know what the terms are in unity land

#

but UIElements is architecturally React

#

at least aspires to be

undone coral
#

would you know how to achieve this in react code?

#

modern react?

#

UIElements should have an equivalent of useLayoutEffect

#

you are not the first nor last person on earth who needs to know the size of a layout in order to do something

urban warren
undone coral
#

so i really feel like if you are fishing for the internal methods you are doing something wrong

#

you should try my asmdef approach just so you ycan see for yourself

urban warren
undone coral
#

that those events are a world of hurt

#

i don't think you do

#

you can do that easily by checking every frame if there is a new child, and move on

undone coral
#

and add a reference to com.unity.ui in it

urban warren
undone coral
#

list difference is a known quantity

#

i don't know if you need this approach though

#

writing UI is tricky

urban warren
undone coral
#

'previous' children, but that seems needlessly expensive and complicated
you should look at the UIElements source to understand that there is an incredible number of "lists"

#

an incredible number of lists this frame compared to lists the previous frame

#

and it has no meaningful impact on performance, because computers are purpose built to compare lists

#

based on how hierarchyChanged's source code

urban warren
#

Well compared to simply using the internal event that does exactly what I want 😛

undone coral
#

it seems like it is only used by UIElements editor code

#

it doesn't do what you want

#

where did you get the idea that it does?

#

its name?

urban warren
#

No, because it is called from the hierarchy's .add method

undone coral
#

have you looked at the source?

urban warren
#

Yup, that is how I found it.

undone coral
#

well

#

we can talk about how to make a split pane view

#

or we can talk about something that doesn't make sense

#

it's internal for a reason

#

it doesn't do what you want

urban warren
#

lol what?

undone coral
#

i'm not sure why you need to know when you add elements using this event in particular*

#

it sounds like you are chasing a theory about efficiency

#

it's not how this stuff works

#

in order to avoid having to compare a list of 1 element to another list of 1 element... you are doing a big to do

#

can you maybe talk about how you are using this event?

#

why is a list of previous children expensive?

#

since when?

#

like what is the idea

#

i can see why you want to know when the children have changed

#

but you do not need this event to do that

#

and it will not provide a meaningful efficiency gain

urban warren
#

I need to add a GeometryChangedEvent callback to all the children of a specific VisualElement. So I need to know when one is added or removed so I can register or unregister the event.

undone coral
#

because you are trying to calculate the size of something?

#

help me undestand the big picture here

#

because you could just have a dictionary of the children you've called this thing on

#

and move on

#

it will not have a meaningful impact on performance

#

i don't see much behavior in the ui elements code that depends on this event

#

which makes me really skeptical you need to use it

urban warren
#

My main problem with using the list/dictionary approach is that when it will be called is not specific. Which may not be the end of the world but I feel like it makes things messy imo.

When a child is added/removed I need to also add/remove a divider for it (used for resizing a child)
Along with that I need to register a GeoChangedEvent

undone coral
#

okay

urban warren
#

Right now I am opting for just having a AddPane(..) and RemovePane(..) methods that you use instead of the normal Add(..) and Remove(..)

undone coral
#

component

#

in react

#

which does not use componentDidMount

#

so you could translate it directly to UIElements provided you knew what this stuff did

#

are you sure AttachToPanelEvent isn't what you need?

#

for your constructor?

#

your pane should look like

#
<SplitPane>
 <Pane> ... </Pane>
 <Pane> ... </Pane>
</SplitPane>
#

react only reruns render when state changes

#

it appears to rerun when the children change, which is fine

#

that is just comparing two lists

#

obviously in the browser it is running in real time without a meaningful performance impact

#

so in my opinion you are overthinking this

#

anyway writing UI code is a long journey

undone coral
#

this guy did a really good job

#

UIElements IS "Unity React"

#

so if you can understand his stuff you can get a super high quality split pane

undone coral
#

to spawn enemies until you have reach a maximum spawned, then once those enemies die, resume spawning?

#
async UniTaskVoid SpawnerStateMachine() {
 var enemies = new List<Enemy>();
 var maxEnemies = 4;
 var spawnPeriodSeconds = 0.3f;
 // for as long as you want...
 while (true) {
  // if the number of enemies is too few
  if (enemies.Count < maxEnemies) {
   // wait a beat
   await UniTask.Delay(TimeSpan.FromSeconds(spawnPeriodSeconds));
   // spawn one
   enemies.Add(Instantiate(enemyPrefab));
  } else {
   // wait until an enemy dies / is destroyed
   await UniTask.WhenAny(enemies.Select(enemy => enemy.GetAsyncDestroyTrigger().OnDestroyAsync());
  }
 }
}
#

that's it

#

you can pass cancellation down if you need

#

i don't want to make it too arcane

#

because ti should be clear how you can pause this

spare pond
#

Check thread that i created

undone coral
#

yeah

#

it seems

#

bad

#

your thread

spare pond
#

why

undone coral
#

what i wrote here is much clearer

#

well what's your goal?

#

is it to spawn enemies until a certain number are on the battlefield

#

and then as they die, resume spawning them?

spare pond
#

yes

undone coral
#

okay

#

do you see how the code i wrote expresses almost verbatim that logic?

#

you don't need this actual spawn preserve forget stuff...

#

you don't need the awaiter

#

or actual spawn versus spawn

#

the point of unitask is that you can express things like a game loop / a state machine / a behavior

#

does my example make sense @spare pond ?

spare pond
#

Ok let me implement WhenAny and i will share result

undone coral
#

well my code makes certain assumptions

#

about how your game works

#

so if you don't know what's going on here

#

you're not going to have something that works

#

if your enemies are not Destroyed

#

then that trigger will never fire

#

you could also monitor the list of enemies until it changes some property

spare pond
#

Im using objectpool so my objects not getting destroyed

undone coral
#

right

#

so you gotta understand what's going on in the code

spare pond
#

I cannot use whenany because its takes array of elements when i cannot give that array coz im not allowing to

undone coral
#

it's up to you if you want to use the bad logic in there

#

in that thread

#

it doesn't make sense

#

i'm not sure what you mean by you cannot give that array

#

surely you have a way of knowing which enemies are spawned

#

there are a lot of ways to achieve that

#

you can adapt the example i wrote for an object pool

#

the key thing i'm illustrating is how to write game logic using unitask

#

you just write it

#

you try to express in written words what your logic should do

#

and the magic is that you can turn that english language into code

#

you seem like you are concerned about "garbage" in the thread

spare pond
undone coral
spare pond
#

I can expose this to a method Gameobject[] GetObjects() but will it allocate memory?

undone coral
#

this memory allocation will not matter

#

why use unitask if you are concerned about memory allocations

#

you're using event which allocates arrays

#
    private void OnEnable()
    {
        _stash.OnRemove += (c) => StartSpawn();
        StartSpawn();
    }

    private void OnDisable()
    {
        _stash.OnRemove -= (c) => StartSpawn();
    }

^delegates allocate and there is absolutely nothing you can do about it

#

but you just didn't know that

#

and yet... nothing happened to your computer program?

final steeple
undone coral
#

why use Unity if you are concerned about memory allocations*

#

it's just to say that if this is your concern

#

this maze is not meant for you

#

anyway, i wrote you an elegant example you should think about

#

you can look at UniTaskCompletionSource to see how you can "signal" a task

#

which is a superpower

spare pond
#

because I'm making a game for mobile and user will touch this spawner alot

undone coral
#
var destroyed = new UniTaskCompletionSource();
destroyed.TrySetResult(...);

// elsewhere

await destroyed;
undone coral
#

you are already allocating somewhere

#

people go on this journey... the issues with allocations are due to flawed logic

#

which is why i am suggesting a more elegant approach to describing your game logic

#

using unitask

#

that's why people use it

#

the elegance of it all

#

that avoids the mistakes where allocations matter

#

but you're already doing _stash.OnRemove += (c) => StartSpawn(); which allocates

#

it's unavoidable. you simply cannot use public event ... without allocating

#

indeed, you will be allocating everywhere all the time in Unity

#

allocations in and of themselves do not matter

#

but when they do matter, it's because it's a huge allocation, happening every frame, with some dumb logic

#

not because you are using event or WhenAny

undone coral
#

if your reaction to discovering you are allocating is

#

to somehow explain away this allocation

#

that's a good part of the journey but one which you can do on your own

#

because surely, if you think that _stash.OnRemove is okay because it happens very rarely

#

so does GetObjects()

#

i am glad you are considering this perspective though @spare pond because it will make you a much, much better programmer

#

think of it as an expanding brain meme:

  1. all allocations are bad
  2. some allocations are okay
  3. when allocations are bad, a different mistake was made
  4. allocations do not matter, because i don't make those mistakes
#

@final steeple c'mon that's a pretty good one

final steeple
#

lmao

spare pond
#

@undone coral In WhenAny part how can i instead of checking for destroy trigger
check for trigger that is called when removing an object from the collection

urban warren
# undone coral https://github.com/tomkp/react-split-pane/blob/v2.0.3/src/SplitPane.js this is a...

Maybe if I was more familiar with JS and also React I could translate it to C#. But even so, it looks like the architecture is quite a bit different than UITK (though definitely has similarities), so I'm not really sure how much could really be carried over.

And if it does things the way I think it might, it wouldn't follow the same design pattern that UITK uses for its elements.

I was wanting to get the hierarchy change event so that I could then create a UITK event for it, then I could something like RegisterCallback<HierarchyChangedEvent>(..) and it would be nice and clean and could be used else where.

#

I appreciate the suggestions though! 🙂

warm sinew
#

How to debug development build in VS?

formal lichen
#

Is it possible to use the System.dll for .NET 4.5 with Unity?

final steeple
#

Why would you want to do that?

formal lichen
#

Tested it, got it working

#

needed the newer TLS version

undone coral
#

this will let you await in one place and TrySetResult (i.e. signal, or finishing awaiting and return a value) in another place

spare pond
#

ok, thanks

undone coral
#

anyway it's close

urban warren
#

Its fine though, using my own AddPane() method will work fine enough

brittle pumice
#

Quick question

#

Can I execute a static method using the -executeMethod from a custom package folder ?

urban warren
brittle pumice
#

So I have a custom package in my project eg Package/MyCustomPackage

#

I would like to execute a static method with exeMethod flag from that package instead of assets folder

brittle pumice
#

Command line argument -executeMethod

urban warren
#

Oooh, yeah should work fine

brittle pumice
#

Do you have a ln example, I seem to be able to it fine from a script in assets but it can find that script in my package

urban warren
#

No sorry. I just know how Unity handles that stuff internally mostly so given that info, it should just work.

#

But really at the end of the day it is just a guess on my part

brittle pumice
#

Ok , must be a way to path to a package

#

Seems like a reasonable assumption

brittle pumice
#

Ok user error

#

Works fine

misty glade
#

I have a Unity class with many events that I need to subscribe in Awake() and OnDestroy(). I'd like to stop forgetting to write the += and -= in those methods.

Anyone have a nifty/clean way to do something like:

private void Awake() 
{
  SubscribeEvents(true);
  // NetworkManager.OnServerSendStartBattle += HandleServerStartBattle;
}
private void OnDestroy()
{
  SubscribeEvents(false);
  // NetworkManager.OnServerSendStartBattle -= HandleServerStartBattle;
}
private void SubscribeEvents(bool isSubscribing)
{
  // ?? 
}

Obviously I could just if/else the entire thing but.. I was wondering if there were something you geniuses could come up with that's cleaner. 🙂

copper wind
sage radish
misty glade
#

no real reason, no

#

should I be doing that work in OnEnable/OnDisable?

sage radish
#

Well, it will behave slightly differently. If you do it in Awake/OnDestroy, your scripts will still react to events when they are disabled

#

Which is confusing

#

But maybe desired in some cases

humble onyx
misty glade
sage radish
undone coral
#

see unirx's implementation of AddTo

misty glade
#

Does that RemoveFrom() implicitly later?

#

my issue is that I wanted to get away from adding a line that +=s and one that -=s because it's getting gnarly:

undone coral
#

yes

misty glade
undone coral
#

that's what AddTo does

#

it ties the lifetime of a subscription

misty glade
#

cool, i'll check that out.. i keep hearing about unirx and just avoiding it

undone coral
#

to a variety of things, include a gameobject, component, etc.

undone coral
# misty glade

yeah... you wanted to do

BattleManager.instance.gameEvents
  .OfType<BattleDefeat>()
  .Subscribe(bd => ...)
  .AddTo(this);
#

and model your events hierarchically

#
interface IHasTarget {
  GameEntity target {get;}
}

interface IHasSource {
  GameEntity source {get;}
}
abstract class BaseEvent {
 string description {get;}
}

abstract class GridEvent : BaseEvent, IHasTarget, IHasSource { ... }

class MoveGridItemEvent : GridEvent {}
class StealGridItem : GridEvent

// one kind of ui
gameEvents.OfType<GridEvent>()
  .Subscribe(ge => RenderAnimatedGridArrow(from: ge.source, to:ge.target)
  .AddTo(this);

// another kind
gameEvents.OfType<BaseEvent>()
  .Window(5)
  .Subscribe(events => SetHistoryTray(events))
  .AddTo(this)

void SetHistoryTray(IList<BaseEvent> events) {
  Enumerable.Range(0, events.Length).ForEach(i => 
   view[i].text.text = events[i].description) ...
} 
``` @misty glade
copper wind
# humble onyx you added the scope in the project settings and added it via the package manager...

Yeah, I added it in the project settings as the documented instructed. I do see where other Visual Pinball items have been added to the existing menus of the unity editor, like there is now a Visual Pinball menu in the Component menu.
I do have errors in the console but they seem to be talking about game objects and materials, which I think would be fixed if I could do the next step of importing a table that's been built in VP, which I have some of already.

The Visual Pinball menu item is suppose to have an option in it to import those .vpx files.

humble onyx
#

if unity throws an error when compiling some code it will not finish compiling and you will not get the menus

misty glade
#
void SetHistoryTray(IList<BaseEvent> events) {
  Enumerable.Range(0, events.Length).ForEach(i => 
   view[i].text.text = events[i].description) ...
} 

what's this bit do @undone coral ?

undone coral
#

oh you have a history tray

misty glade
#

ahhhhh, i get it

undone coral
#

generically show the description of ht eevents in it

misty glade
#

since the .descriptions on the base event

undone coral
#

yeah

misty glade
#

OK - this is a little wacky for me but looks really cool

undone coral
#

so all this stuff you want to do with the events

#

it can be more general

#

here's something really mindblowing

misty glade
#

this might be the solution to my biggest problem right now - animations

undone coral
#

yeah

#

that's what i'm about to show you

misty glade
#

While you type, let me tell you my problem and you'll see why my current implementation sucks. I have this chonker Battle state object that is maintained in the battle manager. When the server tells me something's happened (actually, a lot of somethings - like 10+ "actions"), I update the Battle object and emit all these events in order so the UI can animate them. The UI literally just catches all the events and adds them to a coroutine spooler to unspool them and play them. The problem is the UI can't tell what the data is DURING the animations because the Battle object in the manager is "in the future" after all the animations have played.

So if there's two "gets hit for 10 HP" actions, after the first one is played, the UI doesn't know what to display (-10? or -20 hp) because that state isn't saved anywhere.

Sooooooo my current solution was to piggyback before/after variables in ALL of the events, which is a massive pain in the dick.

My proposed fix was to create a copy of the Battle state (nontrivial) and have one be the "true" state and another be the "animated/delayed" state. But that sucks too.

undone coral
#
// get all the scripts on your game manager
// that handle events
var eventHandlers = GetComponents<EventHandler>()
  .Where(handler => handler.enabled)
  .ToArray();

// create a thing where when you subscribe to this,
// the events are going to be animated with the
// "right" delays due to animations or whatever
var animatedEvents = new Subject<BaseEvent>();

// get all the game events which may come instantly
// from the server
BattleManager.instance.gameEvents
 .Select(event => Observable
   // process them one by one inside coroutines
   // think of this like a "route handler" in a web
   // app which may have multiple handlers that should
   // process something sequentially and asynchronously
   .FromCoroutine<BaseEvent>((observer, cancellation) =>
     ProcessGameEvent(event, eventHandlers, observer)))
 // part two of the magic that makes it all sequential but
 // asynchronous
 .Concat()
 // part three: pump the messages into "animatedEvents"
 // AFTER the animations have occurred
 .Multicast(animatedEvents)
 .Connect();

private IEnumerator ProcessGameEvent(
   BaseEvent event,
   EventHandler[] handlers,
   IObserver<BaseEvent> observer) {
 // this is the API for event handlers
 // for example, showing a toast should come from
 // this context object, or making the screen shake
 // or showing a menu
 var context = new EventContext(event, ...);
 foreach (var eventHandler in eventHandlers) {
  // i.e., a coroutine
  IEnumeator processor = eventHandler.Handle(context);
  // workaround for https://forum.unity.com/threads/yielding-a-nested-ienumerator-waits-a-frame-even-on-break.772352/
  while (processor.MoveNext()) {
   yield return processor.Current;
  }
 }
 // you have handled this event
 observer.OnNext(event);
 observer.OnCompleted();
}
``` @misty glade
undone coral
misty glade
#

Give it a moment to explode, I'm still digesting the code hah

#

do me a favor doctor p

#

start doing that lol

undone coral
#

lol

misty glade
#

AHHHHHHH thank you

#

was having trouble picking out the comments

undone coral
#

the snippet has a lot of science in it

#

you can look at the sophisitcated examples of "event handlers"

#

those are straight from spellsource and use different names for things

#

but it's the same idea

misty glade
#

what's the .Connect() method do?

#

just .. subscribes to the observable?

undone coral
#

it's like a "copy these into here" method

#

except at the moment Connect is called, the game events now come in AFTER their corresponding animations have completed

#

then you can subscribe to "animatedEvents" and know that when you get an event via animated events, it will be right when all teh animations are complete

#

including, e.g., the game data at that moment of time

#

which is almost always what you want

#

connect is Subscribe for subjects (which are like mailboxes)

misty glade
#

hm.. interesting.. so like, hang on, you're saying that my "state" doesn't advance until the event is done being chewed on by the subscriber..?

#

I'm not really getting that

undone coral
#

i think look at the sophisticated examples

#

of message handlers

misty glade
#

OK.. I'm going to really dig into this and try to understand it

undone coral
#

this is basically a way to do "execute a bunch of async handlers sequentially, or sometimes in parallel, whatever makes sense)

#

"and give me the opportunity to show the right state at the right time"

misty glade
#

the problem is i'm trying to do something sort of advanced and .. don't really have my head around UniRX as a beginner, so that's not going to work out well

undone coral
#

"or, if i want the latest state, i wanna see that too"

#

well

#

this is how i do, in spellsource

#

in a super non spaghetti code way

#

"let the attack animations play out, but let you do all the actions you can as quickly as possible"

#

kind of like in hearthstone, but even better

#

you can just do all your attacks without waiting for them to animate out

misty glade
#

Right.. that's what I definitely WANT to do because making a "lagged copy" of the entire stateful object just fort he UI to operate on is shit, because everything the UI points to is the "real" copy of the state - i'll have to literally be switching it back and forth depending on whether i'm animating

undone coral
#

yeah in this example you get the lagged copy

misty glade
#

hearthstone is the exact model i'm thinking of

undone coral
#

if you want it

#

well... there you go

#

good luck with this

#

you got the science now

#

this is how you do it without spaghetti code

misty glade
#

it's actually very much how our game works - there's 5-10 actions, each of which animate automatically (like dudes on the battlefield attacking the opponent) but the HP of the interim state needs to be correct

undone coral
#

mmhmm

#

i know my dude

#

i know

misty glade
#

OK thanks - i need to scoop up my brain a bit and stuff it back in my cranium

undone coral
#

lol

jaunty creek
granite viper
#

the error position is weird, but you're probably erroring on line 40

#

if _controller.walkableTiles is empty it will error

sly grove
#

oh sorry - yeah Mad is right

#

I misread your error

#

ArgumentOutOfRangeException is known to be misreported on the closing bracket of the method

jaunty creek
wispy epoch
#

I'm using a URP shader graph in my game that creates an ammunition bar that shows the bullets left in the mag and one dissapears each shot. Works well. I'm trying to use the same exact shader graph in my armory scene however, and the image shows up fine in both scene and game view but not once i play it. So it must be an issue with rendering. Worth noting that the ammo bar was in world space and this is on the UI layer so that could be part of the problem.

Open to other options that would be easier than updating the fill amount of this shader graph for each weapon stat. Im sure i could just have each bar representing a stat level be its own game object that can change sprite/color individually but i feel like having 40 game objects for something like this is bad practice.

urban warren
#

Quick question about how System.Guid works. If I create a new guid, and convert it to a string or byte array, but never recreate the guid after domain reload. Does that mean it can be regenerated again (or more accurately increase the chance of it being generated again)?

sly grove
#

I'm not sure how you converting it to a string or byte array is relevant

urban warren
sly grove
#

GUID collisions are possible but incredibly improbable

urban warren
sly grove
#

Using a pseudorandom number generator

#

as all random numbers are generated

#

it is merely a 128 bit number

urban warren
#

I see. Well thanks!

#

Got another unrelated and less concrete question.
What sort of memory impact do loaded ScriptableObject assets have vs just using normal C# classes?

sly grove
#

there's a native C++ part to them. They need to be manually Destroy()ed

#

so - slightly more impact

#

plus that extra memory management concern

urban warren
#

Right, but I guess I am wondering what the memory overhead is compared to a normal C# class. Like 1000 C# classes vs 1000 SOs

sly grove
#

a bit more

#

like I said

urban warren
#

Yeah

sly grove
#

The SO is basically a normal C# class, plus some fields for the fact that it inherits SO, Plus the native bit

#

whatever is there on the native side

urban warren
#

Yeah, I think I will go without

#

Thanks

urban warren
#

I am converting a GUID to a string to a PropertyName, as doing lookups with PropertyName is several times faster then with GUID, but man does it feel dirty haha

final steeple
sly grove
final steeple
#

It's about them migrating to CoreCLR, .NET 6, etc

sly grove
#

oh ok good stuff

unkempt nova
#

Sounds cool

final steeple
#

Also confirmed NuGet support finally

sly grove
#

ooooh

#

sick

final steeple
#

Also replacing asmdefs with the modern SDK-style csproj

#

(asmdefs still work, but they'll be converted behind the scenes)

unkempt nova
#

Is it just me, or is the audio messed up?

final steeple
#

Yeah it's doubled lol

sly grove
#

it's messed up

unkempt nova
#

Unity GDC from beyond the void. Nice.

#

AwaitableCoroutine sounds interesting

austere jewel
#

Yeah, I'm hoping that'll actually be the point when we can start recommending async without caveats 😄

final steeple
#

The cancellation token stuff actually shipped in the recent 2022.2 alpha

austere jewel
#

If it has a cancellation token that automatically cancels based on playmode changes, and maybe object destroy stuff it'll be pretty nice

final steeple
#

Though I have some concerns with how it was implemented at the moment

austere jewel
#

What shipped? AwaitableCoroutine?

final steeple
#

Nah, every MonoBehaviour has a CancellationToken property you can use now

austere jewel
#

Oh weird

final steeple
#

and the Application class has a global cancellation token representing when the game exits

#

Which is really nice

#

but having one on every MonoBehaviour is going to result in a bit of memory overhead with how they've implemented it

#

(a lazily allocated CancellationTokenSource on every MonoBehaviour)

austere jewel
#

AwaitableCoroutine sounds more like the right way to do it based on what was briefly mentioned in the talk. Might be worth asking for them to elaborate in the .NET thread

final steeple
#

coroutines are common, but are still the "minority" in the realm of MonoBehaviour instances, so you'll end up with a ton of memory wasted on null pointer storage

austere jewel
#

Agreed

final steeple
#

like an enemy might have 6 components, only one of those will perform coroutines

#

So those 5 other components don't need to store a token

#

I imagine it'll add up fast in a big project, since that's 8 bytes of memory for every single MB instance

#

4 bytes on 32-bit

sly grove
#

a piddling few KB at worst

#

but sure

final steeple
#

Either way I think an external storage location would be a better idea

unkempt nova
#

Seems worth it for potential ease of use

final steeple
#

Some kind of mapping from instance ID to cancellation token

#

Then it can still be exposed as a property on the MB, but doesn't waste memory when you don't use it

austere jewel
#

I'm just excited about not having my own implementation to handle exiting playmode

final steeple
#

I imagine they already plan to make that optimization, the feature JUST shipped in an alpha after all

#

but I wanted to bring it up anyway

final steeple
#

Now I just want a proper accessor for the main thread's sync context PepeHands

austere jewel
final steeple
#

A synchronization context is how you queue work on another thread

#

So you can just do MainThread.Post(method, null); and it'll get called on the main thread

#

The main reason to have a proper accessor is that some other code could get called before the SubsystemRegistration callback and change the sync context, and then it won't get the one for the main thread

#

An extremely unlikely occurrence but it'd be nice for it to be an impossible one

#

For reference, the sync context is also how task continuations are called

#

So when you await Something(), the rest of the method after the await is queued on the sync context, which is how it'll stay on the main thread normally

urban warren
#

I got another API design question. I have a custom collection type that will have methods that function the same as the ones in ISet such as IsSuperSet(..) and Overlaps(..), along with ones that function similarly and will have the Exact word in them (ie. IsSuperSetExact(..), OverlapsExact(..)).

So here is the question, do I do my naming scheme and do ContainsAll(..), and ContainsAny(..) along with ContainsAllExact(..), and ContainsAnyExact(..) which to me is a bit more intuitive. Or do I use the naming in ISet for consistency?

final steeple
#

Arguably it's better to follow existing conventions so that the knowledge is transferrable between different types, but if your type implements the ISet interface you can technically do both

#

Just implement the ISet methods explicitly so they're private to consumers using the concrete type, but usable by casting to the interface

urban warren
final steeple
#

That said, I'm a bit biased -- I have the meanings of the method names for most of these etched into my brain with a laser

#

So I don't really feel confused by them, but others may disagree

austere jewel
#

What's the Exact bit do 🤔

urban warren
#

Yeah, I don't really use the ISet interface (or implementing classes) much so I kind of gotta think about what some of the methods do sometimes

final steeple
#

Would be nice if Unity shipped the proper XML doc files so you could just hover over the methods to get an explanation like in any other C# project 😔

austere jewel
#

Which methods don't have the comments show?

final steeple
#

Every single BCL method

#

and type, and field, and property...

urban warren
# austere jewel What's the Exact bit do 🤔

It is a collection of nodes of a tree, and by default Contains will check for the node but also if any of the nodes in the collection have the specified node as a ancestor. So the Exact variants of the methods will only check if the collection has the specified node and not check ancestors

final steeple
#

Unity doesn't ship the framework doc file, so you just don't get any of it

austere jewel
#

Maybe I'm just used to Rider where it finds it all automatically, or maybe I'm looking at different stuff

urban warren
final steeple
#

That's what I mean

#

BCL = Base Class Library = .NET

austere jewel
#

Another thing where Rider's just putting in work I suppose

final steeple
#

Rider likely includes the XML file itself, yeah

#

As a workaround though, you can add the netstandard.xml file yourself and it works

urban warren
final steeple
#

This file goes in uh

#

sec

#

Editor/Data/NetStandard/ref/2.1.0/

#

and then you'll get the proper doc stuff in VS

urban warren
final steeple
#

Your Unity install dir

#

C:\Program Files\Unity\Hub\Editor\version probably

#

But once you've put it there, it works as expected:

#

It's just unfortunate that it's not included in-box (maybe by mistake)

urban warren
#

OOOH, thank you @final steeple!
Here I was thinking I had installed C# stuff wrong this whole time

final steeple
#

It annoys the hell out of me when I forget to copy it in there lol

urban warren
#

Yeah, I wondering why Unity doesn't include the xml for the base C# doc commends...

austere jewel
#

Man I love Rider lol

urban warren
#

(Littered with keywords so I can find this again when I forget ^ )

urban warren
#

(Well now I do thanks to Zombie)

austere jewel
#

Must be a setting somewhere then surely. Or maybe it's fairly new? Are you on the EAP rn?

final steeple
#

Your Rider installation might be using a normal .NET SDK installation rather than Unity's

#

Which would explain why you had XML docs without needing to manually add the file

austere jewel
#

Everything's ticked for me

urban warren
austere jewel
#

Hrm. Maybe Zombie's right and I just have it installed in such a way where Rider's finding it. Or there's another setting somewhere. Good there's a workaround at least 🙂

rose bronze
#

Can anyone please help here?
Has anyone implemented Oauth with strapi as backend?

fiery horizon
#

Hi guys does anyone know if we can use the auto geometry 2d feature via code?

regal olive
#

Hi Guys, I want to build a Match3 Mechanic for mobile. The question now is, should i build it a Canvas or with normal transforms. The Pros for Canvas would be:

  1. Scaling the board, that it always matches the screen would be a lot easier
  2. Grid Layout is also there out of the box, which would also save me some work.
    For the Cons i cant say that much, but i have a feeling that there are some pitfalls doing it in a canvas, that I am not thinking of right now,
    What are your guys opinion on this? How would you build something like this?
plucky laurel
#

cons are performance, with large enough grid the layout will eat up quite a lot of perf on any updates to the scene graph

regal olive
#

So which size would a large enough grid have?

#

are we speaking of 10x 10

#

or 1000 x 1000

#

just to have an idea on when is starts to matter

plucky laurel
#

its best to use ui for the whole thing, just be aware that things that require layouting are expensive, and in general changing any recttransform property can be expensive

regal olive
#

And when i want to use particles on the merge field

#

would this become an issue?

#

Performance wise

#

@plucky laurel

plucky laurel
#

particles are not natively supported in ui

#

youd have to use a plugin, from asset store or github

regal olive
#

Yes sure

#

but how is it performace wise

plucky laurel
#

but no particles dont participate in rect updates

regal olive
#

okay

plucky laurel
#

its just a mesh

regal olive
#

thanks

#

thas good to her

#

so you would go with canvas right?

#

🙂

plucky laurel
#

multiple canvases, for base ui, separate one for the "grid" , the grid i would write myself

regal olive
plucky laurel
#

yes, not using it

#

since the grid layout handles all cases it can, you can write a very small and specific code that does what you want with minimal performance impact

novel wing
#

Can you [BurstCompile] normal methods, assuming they only use blittable types? Or is it exclusively Jobs only?

desert oyster
#

Hey I was thinking about updating from 2019.4.15f to 2019.4.37f, but apparently there are some major differences in the canvas scaling area... .WorldToScreenPoint methods are working differently and my whole UI is glitched...

#

Previously I did

Vector3 pos = camera.WorldToScreenPoint(p);
pos /= canvas.transform.localScale.x;

to convert from world space into canvas camera overlay space.... But now its not working. Any can suggest a fix? Thanks
Important note is that my camera viewport rect has 0.956 height, the top bar is cropped out of camera rendering.
I've tried various calculation fixes for this, but I'm struggling with one thing: After changing camera viewport rect the size of the camera overlay canvas does not update until I move the camera a bit.... :/

cloud crag
#

Hi. How to swap two scripts on two different gameObjects?

fickle mango
desert oyster
#

create a temporary go

cloud crag
#

values are needed

#

it'd be great if this was possible
AddComponent<YourScript2>(scriptObj);

#

or as java's every object has .clone();

cloud crag
#

Thanks

fickle mango
#

it's probably easier if you just write your own clone function

cloud crag
#

another quick question
why Can I see private properties?

#

and set it.

#

just updated visual studio

fickle mango
#
public void CopyData(YourScript original)
{
    someInt = original.someInt;
}
fickle mango
cloud crag
lean loom
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;

public class CameraAdjust : MonoBehaviour
{
    #region Get Components
        public GameObject player;
        public GameObject cinemachineObject;
        CinemachineFramingTransposer composer;
    #endregion


    public Vector2 offsetEnter, offsetExit;
    public bool exitEnabled;
    // Start is called before the first frame update
    void Start()
    {
        #region Set Components
            CinemachineVirtualCamera vcam = cinemachineObject.GetComponent<CinemachineVirtualCamera>();
            composer = vcam.AddCinemachineComponent<CinemachineFramingTransposer>();
        #endregion
    }

    // Update is called once per frame
    void Update()
    {
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        //if player enters
        if (other == player.GetComponent<Collider2D>())
        {
            //adjust camera
            composer.m_ScreenY = 0.5f + offsetEnter.y;
            composer.m_ScreenX = 0.5f + offsetEnter.x;
        }
    }
    void OnTriggerExit2D(Collider2D other) 
    {
        //if player enters
        if (other == player.GetComponent<Collider2D>() && exitEnabled)
        {
            //adjust camera
            composer.m_ScreenY = 0.5f + offsetExit.y;
            composer.m_ScreenX = 0.5f + offsetExit.x;
        }
    }
}
#

Hello, I have this code on one object which works

#

the only important part is that OnTriggerEnter2D and OnTriggerExit2D works

#

when I copy the object this is attached to, only one object works

fickle mango
lean loom
#

Yes

#

here is a screenshot

#

a screenshot of each object and the components

fickle mango
#

add a Debug.Log("TriggerEnter) into your enter method to see if it gets called for both objects

lean loom
#

will do, one moment

lean loom
fickle mango
#

Since Start() is called twice with two objects it's probably overwriting something

lean loom
#

So, the Debug.Log activates for both objects but not the rest of the code.

May be an issue with Cinemachine and trying to have 2 objects reference the same camera object

lean loom
#

it seems it had something to do with that, thank you

hollow stag
#

i need help setting up a body system similar to gorilla tag, with the head and arms. i already have the movement mechanics done. i just want to give the players a design so it’s not just hands

half cape
#

hey I need help with a jump. when i turn my player while jumping I spin around the initial jump point.

zenith ginkgo
half cape
#

thanks nobody answered in general

rigid falcon
#

could anyone help me ?

humble onyx
rigid falcon
#

I have been making this helicopter game it works great in the editor but once I build it some of the controls don't work

regal olive
#

So I'm trying to figure out how to make a grinding system in my game. The issue is I don't even know where to start, I just need a way to attach the player to this gameobject once they enter the trigger collider

#

I was trying to send a gif of what i meant but I guess i cant -_-

humble onyx
humble onyx
regal olive
humble onyx
regal olive
#

Yes

wispy epoch
#

So i need some help im pretty stuck. As you can see in the picture, I'm trying to implement a weapon stats upgrade system to pay for stat increases on each gun. I'm using playfab to store player data and this data (the amount of upgrades purchased in each stat) obviously needs to be updated to player data in playfab too. Problem is I have about 15-20 guns to store these 4 level variables per gun. I was looking for a way to store this data in player data of playfab accounts and be able to update a single variable when something is purchased. Then i need to grab the specific levels of the gun selected which would be better if i didnt have to make an api call every time a weapon is clicked on so maybe have some kind of dictionary or something i can read from? I hope im making sense of this

regal olive
humble loom
wispy epoch
humble loom
#

oh playfab my bad. its late lol

#

ironically scriptable objects are still the answer though

#

have SO's function like containers for data pulled down from API calls and you can handle them with simple dependency injection. don't make an API call every click, just let the local version get away from the playfab state until you have a good opportunity to make an explicit save

#

like when you exit the menu

#
public abstract class PlayfabDataObject : ScriptableObject
{
  public abstract void Save();
  public abstract void Load();
}
[CreateAssetMenu(menuName = "Playfab Data / M4A1")]
public class M4A1PlayfabData : PlayfabDataObject
{
  public int DamageLevel {get; set;}
  public int DamageProgress {get; set;}
  public int FireRateLevel {get; set;}
  public int FirerateProgress {get; set;}
  public int MagSizeLevel {get; set;}
  public int MagSizeProgress {get; set;}
  public int ReloadLevel {get; set;}
  public int ReloadProgress {get; set;}
  public override void Save()
  {
    //TODO: update the playfab data
  }
  public override void Load()
  {
    //TODO: override data with playfab data
  }
}
#

something like that

wispy epoch
humble loom
#

i do a similar thing with local saves. each scriptable object knows its own type and instance name and saves/loads itself according to that, completely idiot proof

untold fulcrum
#

Hi folks 👋 . Does anybody here have experience working with Unity Physics in some detail? I am looking for some assistance on a golf ball simulation - specifically the behavior of the ball on ice.

orchid marsh
tight glacier
#

hey how make resize camera in 2d project use c#

#

and resize in script and move smooth

plucky laurel
simple spear
finite burrow
#

Will a public function that grabs a hidden static function get the correct subclass version?

E.G

public static string SaveDataType => "TRACKED"; 
public string GetSaveDataType => SaveDataType;

and then in a derived class

public new static string SaveDataType => "COUNTER";

If I call
SubclassObject.GetSaveDataType()

Will it return base class static ("TRACKED") or the correct one "COUNTER"
but this is a situation in which the derived class is a variable of BaseClass
e.g

Baseclass x = new DerivedClass();
x.GetSaveDataType()
humble pasture
#

How can i create a code 128 Barcode in unity from string?

humble onyx
fresh salmon
finite burrow
humble onyx
humble pasture
#

in the root folder or assets folder?

#

i put it in the root folder of the project. How can I use that now? Do I have to write using something at the top?

fresh salmon
#

You should have put that in a folder in your Assets/ for Unity to detect and compile it.
The namespace to include can be determined by checking the source code

humble pasture
#

thanks

fresh salmon
#

Ah, you shouldn't be including all the library, just the source code

#

Weird that the outputted DLLs weren't ignored from the start by the user that pushed to the repository

humble pasture
#

alright what do i need?

fresh salmon
#

As Malzbier said, everything in the GenCode128-2.0\src\GenCode128\ folder

humble pasture
#

but that is this

fresh salmon
humble pasture
#

i just copied it

fresh salmon
#

(you can get rid of the .csproj)

#

You should have 4 files under a folder in your Assets/

humble pasture
#

this is in the src/GenCode128 folder?

#

wait

fresh salmon
#

idk where you found these bin and obj folders though

humble pasture
#

yeah i downloaded this but i need not the master

fresh salmon
#

master is the branch the download originated from, it's not relevant

humble pasture
#

alright

#

done

#

but now there is this error

fresh salmon
#

Yep, because that code isn't made for Unity, it uses things in the System.Drawing namespace, that are not available in Unity

#

So you need to convert the bit of code that generates the image barcode to something compatible with Unity

humble pasture
#

oh damn

#

how can i make a bitmap in unity?

fresh salmon
#

It shouldn't be hard, from what I can see they just use Image and FillRectangle to draw the bars.
You would use a Texture2D for it to be compatible with Unity

humble pasture
#

okay

#

Maybe im to dump for this but how can i use the texture2D?

fresh salmon
#

I have never tried to create and modified textures at runtime, so no idea

#

Google time!

humble pasture
#

yess

stuck onyx
#

why i cannot update the load screen while im loading my game syncronously?
i try to upload the screen at some parts of the code doing...

    loadingUIRef.UpdateLoadingScreen(description, currentPercentage); ```
#

but they dont update the loading UI

umbral basin
humble pasture
#

i maybe already have a solution @umbral basin but thanks

umbral basin
#

Good luck

humble pasture
#

Thanks

#

how can i cast the texture2D to an Image?

#

alright its kinda working

stuck onyx
#

can someone tell me why my UI does not update while my loading script is running?

sly grove
#

Not without seeing your code, no.

humble pasture
#

I DONE IT GUYS I LOVE YOU ALL

fresh salmon
#

"ABC"

#

Nice

glossy iron
#

how long have you guys been using unity for?

stuck onyx
#

UI gets blocked because of the continuous expensive sync calls, solved by changing the method to a coroutine and do yield return null whenever i want to update.

compact ingot
quartz stratus
glossy iron
#

no i mean like u guys r advanced

#

so how many years have u been using unity

#

😏

#

just curious

grim basin
#

I have general C# intermediate question that I can't seem to find an answer for anywhere else. So I'm hoping someone here may have an idea: I am still struggling trying to use ENCAPSULATION properly. So in my base class (Animal) I setup the encapsulated property here:

   private TMP_Text speechBubbleTMP;
   public TMP_Text SpeechBubbleTMP
   {
       get
       {
           return speechBubbleTMP;
       }
       set
       {
           speechBubbleTMP = value;
       }
   }

and then in my child class (Bear) I try to set the text and get issues when it tries to run :

   {
       Animal animal = new Animal();           
       animal.SpeechBubbleTMP.SetText("Test encap");      // ENCAPSULATION
       // SpeechBubbleTMP ^^ is a property I am Setting to specific text
   }

I get this in the console when I try to run that "encapText () " method.:

UnityEngine.MonoBehaviour:.ctor () " ```
    And I realize why that's happening-   but HOW can I Set this encapsulated Text property  FROM the child class properly ????
fresh salmon
#

The issue does not come from the encapsulation itself, it comes from the new Animal();, which is not allowed because Animal is apparently a MonoBehaviour.
Use AddComponent<Animal>() to add the script to the current object, or Instantiate to create a copy of a prefab which has the script on.

Otherwise your property is right, and it (the property access and method call) would work as expected.

grim basin
#

@fresh salmon yes someone else suggested the same thing- but that will not work for this because I don't need to add the base class as a component to the child or instantiate it when the child should just inherit from the parent class right?

fresh salmon
#

Then don't make the class inherit from MonoBehaviour if you don't plan on attaching it to a GameObject

sly grove
#

this is all you need

#

if Bear : Animal then YOU are an animal inside the Bear class

grim basin
#

OHHHHHHHHHHHH

fresh salmon
#

Oh yeah I missed that, methods declared in base class can be called from child ones

#

Also since your property does nothing else than getting or setting a field, you can convert it to an auto-property:

public TMP_Text SpeechBubbleTMP { get; set; }

The compiler generates a field for you at compile-time, you don't see it, it works the same as your current code

grim basin
#

hmmmm ok- Im still getting a Null Reference when the encapText runs

#

NullReferenceException: Object reference not set to an instance of an object
Bear.encapText () (at Assets/Scripts/Bear.cs:22)
Bear.MakeSoundAndUI () (at Assets/Scripts/Bear.cs:17)
Animal.OnMouseDown () (at Assets/Scripts/Animal.cs:79)
UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)

sly grove
fresh salmon
#

Have you passed a TMP Text in it

sly grove
#

you need to tell it which TMP_Text you want to set the text for

#

For example:

[SerializeField]
private TMP_Text speechBubbleTMP;``` add SerializeField here and you can drag and drop it in
grim basin
#

THATS IT!!!! thanks you so much @sly grove and @fresh salmon !!

#

I was screwing myself up because I didn't know you could publicly expose it with [SerialzeField]

gilded wing
#

anyone have recommendations for something that could generate some kind of dependency diagram out of vs code? tried googling but nothing seems to be coming up for C# at least

#

like i just want an overview of what is touching what to help me refactor and restructure

#

from an existing codebase

quartz stratus
# gilded wing anyone have recommendations for something that could generate some kind of depen...

I don't know about tools to generate dependency diagrams, but what immediately comes to mind is just good old fashioned namespaces. Start organizing your scripts into folders and subfolders on a per-namespace/sub-namespace basis. Then you'll be able to see at a glance at the top of your scripts which scripts are dependent on what by means of the using statements. If you're really strict about namespaces, this can be super helpful for seeing dependency patterns.

novel wing
gilded wing
#

yeah that's the plan but i thought it'd help to get an overview of what i have to actually figure out where to draw the borders

humble pasture
#

Hey guys i installed sqlite for unity and put the files in but if i want to run the app on android it says "there is no sqlite3" how can i fix that?

errant stump
#

where I can change the name of the folder that is hosted in the appdata/LocalLow= _filePath = Application.persistentDataPath + Path.DirectorySeparatorChar + "UnityDebug.txt";
?

sly grove
regal olive
#

i was able to get a bad version of what I wanted working with splines

quiet bolt
sinful fossil
#

Hey does anyone have a good way to make a texture atlas with varying sized textures? Let's just say that I need it to be like that please thank you!

floral flume
#

@sinful fossil I used to use a paid utility called TexturePacker

#

but since switching to Spine2D, it handles my atlasing for me