#archived-code-advanced

1 messages · Page 37 of 1

tropic stag
#

@undone coral again I really appreciate your help and unirx suggestion. I just saw a tutorial where someone does:

        .Where(_ => Input.GetMouseDown(0))
        .Timestamp()
        .Where(x => x.Timestamp > _lastFired.AddSeconds(_fireRate))
        •Subscribe(x=>{
            weapon.Fire0);
            lastfired = x.Timestamp;
        });

Am I correct in thinking it would be more in the spirit of unirx to replace the timestamp + where with .Throttle(TimeSpan.FromSeconds(_fireRate))?

sweet summit
#

Is there a good approach for allowing any optional parameters on a method?
I have a method that has many overrides OnCallback(string callbackName) where some of the overrides include optional parameters like a byte or vector.
Would it be bad practice to do one method OnCallback(string callbackName, Object obj) with an object or something more universal?

#

So far ive been able to condense my needs into 5 different overrides

#

name,
name, byte
name, byte, vector
name, byte, vector, quaternion
name, vector

jolly token
sweet summit
#

I see, it seems like it would be a pain to make sure the objects are valid too

jolly token
#

Just make overloads

sweet summit
#

Mmk, I think as I develop it will become clear what is needed or not.
5 doesnt seem to bad, adding more doesnt seem to bad either

jolly token
#

For things like Vector or byte you could have optional parameter with default

sweet summit
#

Yeah my first implementation was only name and an optional byte=0

#

This is being used for an ability system to allow some things to be handled by a networked AbilityManager script

#

like OnCallback("SpawnWeaponEffect", 0) which invokes on slot 0

#

not every ability needs every overload though, just override it as needed

jolly token
#

I'd prefer to hide something dirty like that with source generation or such

sweet summit
#

What do you mean?

jolly token
#

So business code just uses compile time types safely

sweet summit
#

So something like an enum or constant rather than string literal?

jolly token
#

Like automatically generated stub

#

I don't exactly know what your setup is but you could hide that you are using string with generated code

sweet summit
#

I see what you mean

#

Since currently all the callbacks are using method names i'm basically just using nameOf

#

then a switch on the invoking side to check the string

#

There were a few cases I wrapped the callback so that i dont have to send an extra string over the network

undone coral
#

that's not how firing works

#

for most games

#

it wouldn't be right to throttle the input

#

it just speaks to how idiosyncratic most inputs are

#

i don't htink that tutorial is very good

#

the plus side of unirx though is that it was extremely easy to comprehend what would happen / what the code is trying to do

#

because it's so succinct

#

and that's why it was obvious to me it was wrong in terms of delivering the wrong user experience

#

it is almost a throttle*

tropic stag
#

out of curiosity: how so? (but the original example with timestamp + where() was wrong in the same way? meaning a throttle provides the same behaviour?)

undone coral
#

most of the time it's a "ThrottleFirst"

#

for lots of weapons it's like there's a short cooldown after you fire successfully during which another input will NOT schedule a second firing

#

e.g. for weapons with very slow firing rates

tropic stag
#

I'm going to have to read both this and throttle docs, cause I though what you just described (cooldown after fire) was a throttle...

undone coral
#

unfortunately in c#, .Throttle(TimeSpan.FromSeconds(_fireRate)) is debounce

#

😦

#

sorry

#

that's just how it goes

#

unirx has throttlefirst though

waxen sinew
#

#💻┃code-beginner message i hope that would be the right place for that since the issue seems pretty complex and hopefully someone can come up with any solution to this, id be very thankful for any ideas. more info in the thread

real blaze
#

hi, does anyone have an idea to what this error might be pointing to? surely it's not trying to strip mscorlib. ( right? 😅)

  • this error is a IL2CPP build error, and to my knowledge, happens not during the stripping but during the c++ conversion
#

here's the log in text, if the image is too tiny

System.InvalidOperationException: One or more shared enum types could not be found.  Was the embedded mscorlib.xml file present when UnityLinker Ran?
Missing types were
[System.SByte, ]
[System.Int16, ]
[System.Int32, ]
[System.Int64, ]
[System.Byte, ]
[System.UInt16, ]
[System.UInt32, ]
[System.UInt64, ]
flint sage
#

That sounds like a bug in Unity

real blaze
#

2021.2.13f1

flint sage
#

Do you have that file that lets you ignore specific classes/namespaces?

#

I forgot what it is called

#

And what happens if you disable stripping completely?

flint sage
#

Yeah

real blaze
#

nope we're avoiding that altogether

#

the stripping is set to minimal already

#

but if that is the case and it has stripped mscorlib, then, I'll have to write this I guess?

<linker>
    <assembly fullname="mscorlib" preserve="all"/>
</linker>
#

put as link.xml in the Assets folder, that is

#

(didn't work)

#

changing the project to 2021.3.8.f1 to test if it works

flint sage
#

Does it also break on different machines?

real blaze
flint sage
#

What about in a new project?

real blaze
#

wait, let me create a thread for it

#

Unity IL2CPP Linux Server build issue

stuck onyx
#

anybody building IL2CPP on mac?

#

we've noticed its not possible to debug on device since Unity 2021

#

but nobody seems to care about this

split folio
#

Maybe not enough mac users for unity devs to be bothered?

craggy spear
#

That's not likely at all

tawny bear
fringe timber
#

Hello guys. Does anyone know how to resize a bone without affecting the child bones? The first approach I had seen was: (1) remove the children from the bone; (2) perform resizing; (3) relocate the children. With this approach, unity calculates the transforms automatically.

What I wanted to know is: what mathematical formulas are involved in this process of calculating transforms when a child is assigned to a new parent.

If anyone knows, it will help me a lot!

This was my attempt at implementation: https://gdl.space/azuhenizir.cs
I left the comments in the code because they were attempts that didn't work out, but they can be useful.

My problem in this implementation is considering the following scenario:
BoneA (resized via script)
-> BoneB (resized via script)
-> BoneC (unexpected resize)

If I resize BoneA and BoneB, BoneC will have a scale that doesn't match the original scale when BoneA and BoneB have not changed.

sly grove
fringe timber
#

it would be like separating the bones from the muscles of the character, right? The bones would literally just be the structure while these bone visuals would be what I called the muscles.

It's a very interesting idea. I would still like to work with the simpler framework, however your solution will certainly be my plan B.

jolly token
fringe timber
jolly token
#

I don't think you get what I said.. you cannot un-scale parent with child's scale if child has non axis-aligned rotation

jolly token
fringe timber
#

The idea would be to change the scales of the X and Y axis (considering the coordinate system of this image).

fringe timber
# jolly token I don't think you get what I said.. you cannot un-scale parent with child's scal...

Ok, I understood what you meant, but I didn't understand in practice if Unity doesn't allow me to scale or if it would be a mathematical limitation of the thing.

But I think the following. Assuming the default scale being 1, we would have the following:
-> BoneA (scale = 2)
-> BoneB (scale = 0.5)
->BoneC(scale = 1)

If I double the size of BoneA, then BoneB should be halved.

Now, if I double the scale of BoneB, BoneC should be halved, right? The result, in theory, would be this:

-> BoneA (scale = 2)
-> BoneB (scale = 1)
->BoneC(scale = 0.25)

But I still don't understand what's wrong with my script.

jolly token
#

You cannot revert this scale regardless of whatever scale value you give to the top cube

fringe timber
honest hull
#

is there ANY way to have bindless textures or something similar for compute shaders in unity?
the whole not having them is making me pull my hair out trying to find an alternative

quaint hound
#

does anyone know why this script isn't working? (error message at bottom)```csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;

public class UIManager : MonoBehaviour
{

private static UIManager _singleton;

public static UIManager Singleton
{


    get => _singleton;
    private set
    {
        if (_singleton == null)
        {
            _singleton = value;

        }
        else if (_singleton != value)
        {
            UnityEngine.Debug.Log($"{nameof(UIManager)} instance already exists, destroying duplicate!");
            Destroy(value);

        }
    }

}

public InputField UsernameField { get => usernameField; set => usernameField = value; }

[Header("Connect")]
[SerializeField] private GameObject connectUI;
[SerializeField] private InputField usernameField;




private void Awake()
{
    Singleton = this;

}

public void ConnectClicked()
{
    usernameField.interactable = false;
    connectUI.SetActive(false);

    NetworkManager.Singleton.Connect();
}

public void BackToMain()
{
    usernameField.interactable = true;
    connectUI.SetActive(true);
}

public void SendName()
{

    //Message message = Message.Create(MessageSendMode.reliable, (ushort)ClientToServerId.name);
    //message.AddString(usernameField.text);
    //NetworkManager.Singleton.Client.Send(message);



    NetworkMessage message = new NetworkMessage();
    message.AddString(usernameField.text);
    NetworkManager.Singleton.Client.Send(message);

}

}

frail kestrel
#

And also, it's because it doesn't know what NetworkMessage is: NetworkMessage message = new NetworkMessage(); so you are probably missing a class NetworkMessage or some package.

sly grove
keen cloud
#

would you guys make methods like this static

#

probably does not need to be in the advanced section lol

#

like when would you choose to make a method static

jolly token
keen cloud
#

okay cool so this is just internal stuff

#

so static it is

#

if every method in this class is static is that when you should just make the class static

sly grove
#

that's the only time you can make the class static

keen cloud
#

hm

#

okay lol

sly grove
#

also - only if it has no instance variables

keen cloud
#

makes sense i was on the path of static is evil but now im going the other direction with some of my classes

#

that fall under this category

jolly token
sly grove
#

static classes are good if you have a bunch of reusable, stateless utility methods basically.

#

Think Mathf

jolly token
#

Mathf ironically struct

sly grove
#

lol

brisk pasture
#

static methods and classes are fine

sly grove
#

conceptually though

jolly token
#

Yeah lol

brisk pasture
#

but lots of static state is just asking for future troubles

keen cloud
#

i would like to remove static state but add like stateless static classes

#

that just do things

#

one thing

jolly token
#

You'll also have to use static class for extension methods

undone coral
#

are you on an apple silicon mac?

undone coral
#

i would create a few different rigs. i wouldn't modify the bones' dimensions at runtime. you have to use external tools for animation retargeting if you want it to look good

little minnow
#

Guys does anyone know something about tilemaps? I want that if I break my tile block, that it can spawn back on the available places... does anyone have a suggestion?

dapper cave
#

When doing Instance(instanceInScene) at runtime it creates a copy of a gameobject, and it seems to include all references too. The odd thing is, if I do .GetChild(0) on one of its transform, I get zero children even though in the Hierarchy view I can see those children. Any idea why?

thin mesa
dapper cave
#

and... fixed

vestal condor
#

what makes an instantiation call more expensive than another?

shy meadow
#

Is there a way to exclude native plugins from dedicated server builds? I can use define constraints for managed plugins

undone coral
#

i wouldn't overthink this

#

i remember this is painful

shy meadow
#

Just for minimizing the build artifacts, but for some, there might be license implications. You're right though, deleting/keeping them is perfectly fine since the server doesn't have the managed libraries that do call into the native plugin

shy meadow
#

We have build scripts for our project, so this is what I did for reference:

    private static PluginImporter _fmodstudio = 
        AssetImporter.GetAtPath("<path-to-plugin>") as PluginImporter;

    private static PluginImporter _fmodstudioL = 
        AssetImporter.GetAtPath("<path-to-plugin>") as PluginImporter;

    private static bool ServerExcludeFMOD(string _)
    {
        return false;
    }

    [MenuItem("Tools/Build/Server")]
    public static void BuildServer()
    {
        _fmodstudio.SetIncludeInBuildDelegate(ServerExcludeFMOD);
        _fmodstudioL.SetIncludeInBuildDelegate(ServerExcludeFMOD);
        
        // more build logic...
    }
undone coral
undone coral
#

what's up with the icons

#

maybe you called .getchild on the wrong thing

half oasis
#

Maybe my previous question is too simple for the code-advanced channel 😅

light vine
#

I have a question in regards to null checks. I understand null propagation/null coalescing bypasses Unity's equality operator override on UnityEngine.Object. However this still implies that if the C# reference itself references null it should return true until it is assigned.

#

I assume this behaviour has to do with Unity's serialization?

tawny bear
coral folio
light vine
coral folio
#

I got nothing, personally, but it's fascinating.

light vine
#

But in this case the variable wasn't assigned in the first place

thin mesa
#

have you perhaps serialized the field or have your inspector in debug mode? pretty sure those will both use unity's fake null until it has been assigned (at least in editor, not sure about in build)

light vine
#

What is extra weird is that I get this when I enter playmode, but when I exit and re-enter playmode it is true true which is what I would expect

coral folio
#

See, in the :old-person-icon: C++ days, that would be uninitialized memory or something. But I presume C# doesn't do things that way, because... 🪄

light vine
light vine
thin mesa
light vine
#

C# is essentially std::shared_ptr<> galore

thin mesa
light vine
#

Yup it was serialization after all

#

The attribute did the trick

#

But I can't replicate this on another Unity project so this has got to be Odin Thonk

#

Seems like I might have a fun thing to report for the guys at Sirenix

thin mesa
#

try the other project with the inspector set to debug mode and it will probably have similar results. i also wouldn't be surprised if odin did that intentionally for the same reason the debug mode inspector does it

light vine
#

"does it intentionally" you mean secretly assigning a UnityEngine.Object as a result of the serialization process?

thin mesa
#

seems like it's just the normal fake null you should be expecting with objects deriving from UnityEngine.Object and not actually a real instance

light vine
#

So for example I have the same setup with Animator and other components but only the RigidBody2D was a problem

#

Oh wait right I forgot to remove NonSerialized

#

nvm kek

light vine
#

If in the serialized data the UnityEngine.Object isn't assigned why not assign null when deserialized?

thin mesa
#

this is part of why you should never use null operators and only use == to check for null with anything deriving from UnityEngine.Object

light vine
#

I understand that. I still wanna understand what is going on x)

#

Cus clearly my understanding of why I should avoid bypassing unity's equality operator override is not complete

#

Especially considering I can turn a 185 LOC file into a ~35 LOC file

stuck onyx
#

then we changed to unity 2021 and no more debugging, breakpoints fail and app freezes

tawny bear
#

Did you update all the stuff associated to a new version of Unity?

#

Packages etc

stuck onyx
#

im now on a silicon mac but in march i tried unity2021 on an intel and it was the same

#

its an issue in the rider's issueboard

#

but no one cares

stuck onyx
#

but worst thing is i installed VS and debug breaks too

tawny bear
#

I don't know just the common things you'd do alongside with upgrading to a new version of Unity, really

stuck onyx
#

so, we already doubt its rider's fault

tawny bear
#

Other than that I don't know anything about this topic

stuck onyx
#

we have updated all the necesary packages yes

tawny bear
#

Is it breaking for several devices?

stuck onyx
#

its not a problem of packages thats for sure, something's different on unity 2021 on standalone debug and breaks visual studio and rider

#

that im not sure i just have 1 testing device, but i've contacted other people in rider's forum and same is happening for them

#

the factors seem to be MAC, I2LCPP and unity 2021

#

mac im not 100% sure

#

this problem has been dragging since last april

#

considering rider is a paid software is quite embarassing

#

but considering debugging breaks on VS too....

tawny bear
tawny bear
stuck onyx
tawny bear
#

Fair enough

stuck onyx
tawny bear
tawny bear
stuck onyx
#

ill try that

tawny bear
#

Yeah I'd try that, see if it's just a "faulty" project

stuck onyx
#

plus im on mac, VS sucks on mac

#

😄

tawny bear
#

What's so bad about it on mac?

stuck onyx
#

well this last version i installed seemed better than the last one

#

but the first one i tried... (4 years ago maybe?)

#

it was like a lite version, i dont know how to explain

#

maybe i installed a wrong version, i was noob with mac back then

#

but it was extremely uncomfortable to work with

#

like.... an improved mono

#

was it called mono? that ide?

#

yeah something like that

#

anyway thanks for the idea ill try it

tawny bear
#

VS 2022 is especially nice

#

(VS 2019 is the standard that "comes" with Unity)

stuck onyx
#

probably the 2019 is the one i tried

#

back in the days

tawny bear
#

Yeah 2022 has new funky features

#

Such as a better intellisense which is very nice

#

I'm never gonna go back to VS 2019 that's for sure lmao

stuck onyx
#

I encorage you to try Rider, even if its a cracked version,

tawny bear
#

I don't wanna type out a whole GetComponent, I just wanna press tab and be done with it lmao

stuck onyx
#

yeah for sure thats one of the most basics things Rider can do

tawny bear
#

Currently trying to decipher a game I wrote 2 years ago

#

Which isn't even in C# Unity, but in Java Processing

#

So that's fun

#

And there are like 0 comments

stuck onyx
#

whats the point on doing that?

#

nostalgia?

#

wghats the game about ?

tawny bear
tawny bear
#

But I can't exactly copy the code 1:1 y'know kek

tawny bear
#

You've these passwords that fall from the sky and you've to drag them in the red/green box respectively to if they're bad/good

stuck onyx
#

😄

tawny bear
#

It's not exactly a game you'd play for hours lol

#

You'd be done with in like 5 minutes really

stuck onyx
#

ahhh i get it

tawny bear
#

Though some might take longer if they decide to challenge themselves with a higher difficulty setting, but I expect the large majority won’t even touch it

tacit socket
#

if anybody knows how to add steam multiplayer, please add me as a friend and help me😬

tawny bear
#

Audacity

craggy spear
tawny bear
#

About time

craggy spear
#

IntelliCode in VS2022 is brilliant ❤️

#

I miss it in Rider

tawny bear
#

Is Rider so much worse in that respect?

craggy spear
#

Rider doesn't have it's own IntelliCode

tawny bear
#

Oh btw I don't really get the hype for GitHub CoPilot, it doesn't seem all that smart, it usually just suggests things that aren't useful kek

tawny bear
obsidian glade
umbral trail
#

I am creating a game object with a mesh collder/rigid body, but sometimes the collider is offset from the visual mesh (they use the same mesh), is there any known issues with this? What would be the correct way to fix it?

umbral trail
#

it is all done at runtime, including generating the mesh

worldly imp
umbral trail
#

nope, all in one

worldly imp
#

Odd

umbral trail
#

(if it helps, the mesh and initial object is generated by turbo slicer)

#

if I change the position in the editor, the mesh collider snaps back to the correct position

#

so I'm wondering if there's some internal state in the rigid body or the mesh collider

undone coral
#

if i paid $5,000/year for unity support i'd ticket it for you lol

stuck onyx
undone coral
#

but i don't

#

i should

stuck onyx
#

ill try to get in contact with them with my shitty subscription

undone coral
#

they're going to tell you to file a ticket with QA

#

which means it will take 9mos

#

and between the time you file and the time they look at it, which is like 9 months, they (QA) asks you to reproduce with the latest version of unity. @crude granite the bad QA filing experience remains the #1 obstacle for me and probably many others from paying for unity support

#

it would be nice if they would prioritize issues filed by sophisticated people

#

instead of issues by payer

hexed meteor
#

Anyone have any tips for starting out with building something like ProBuilder ?

#

Unity really is missing a decent worldbuilding tool like that

long ivy
#

uh, they bought it

sly grove
hexed meteor
true palm
#

Can I use Mono in my C++ plugin to pass arrays? Or do I have to marshal it myself

raw canyon
#

Unity 2022 IL2CPP + System.Text.Json Build Error

coral citrus
#

Hey, would it be possible to pick someone's brain about an issue with a custom render texture?

I'm sure the functionality I'm looking for exists, I'm just not sure where to find it. Basically, I'm running a shader on one update zone (to recolor, say, a sword on a texture), then I clear that zone, make a new zone, and update the render texture again on the new zone with the same shader.

This works fine, but it clears the results from the first zone's update. Is it possible to have the updates "persist"/accumulate?

undone coral
#

the blit shader has these parameters

#

you can render to a render texture representing the whole zone, then blit it to a region of another render texture that you use to texture your model

#

you can explore RTHandles and how the SRPs do this pretty routinely

#

does this help?

#

so you shouldn't be recycling a single scratch render texture for all of your stuff

#

i'm not 100% sure what you mean by zones though

coral citrus
#

i need to look up blit since i haven't seen that used yet but one second, let me see if i can illustrate it

#

this is the "starting" texture- it's all updated to be white, but that's irrelevant

#

this is after i create an update zone on the crt for just this torso sprite- it functions as you'd expect, works great, but if i then update the crt a second time, it'll wipe away that since it's not in an update zone, presumably? or because it's pulling from the base texture again

coral citrus
#

for me anyway

undone coral
#

okay

#

why.... are you doing this

#

what is the idea?

#

based on that image, you know, you can tint sprites

#

right there in the sprite renderer / ui image

#

so what are you really trying to do?

#

using customrendertexture is very built in render pipeline

coral citrus
#

it's a long story and very complicated but

#

the gist is that i'm using something called spine2d, which is just a skeleton animation software for 2d stuff, whatever

#

my issue is that i'm trying to handle a dye system and every slot (aka each of the individual sprites above) needs to be recolorable to any hex

#

the shader does that fine enough, since each sprite needs to have some degree of color detail (it recolors based on the rgb values of each sprite, the default is just white/grey)

the problem arises when you try to apply shaders to each piece of the skeleton, which is what i'm doing in the existing version of the game

#

it causes horrible lag as you'd probably expect from having 10-20 people on screen at the same time, and applying just one shader over the entire skeleton wouldn't really work either

#

so the solution i've arrived at is creating a copy of the texture per skeleton and recoloring pieces of it once, trading horrible rendering lag for a one time cost + some mild memory usage

abstract basalt
#

can't you use the same texture and duplicate the material, and then just change a tint parameter on the material?

#

Is this a custom shader?

coral citrus
#

it is yeah, and because the full texture contains all slot images but different slot images will take different material parameters (e.g. if you want a red sword and a brown shirt)

#

i've tried using multiple materials + a render separator component in spine2d but it has separate issues + it's a lot less performant

keen cloud
#

In what cases should you use interfaces? Like why would you want an empty method

humble leaf
#

To force whatever implements the interface to use it

keen cloud
#

Yeah I’ve looked at examples and I see what it does but I mean what’s the context where it’s best used?

#

Like where would I use it in my code (generally)

sly grove
#

For example if you want to write code that raycasts into the world and "interacts" with things, you might want an Interactable interface

#

so it doesn't matter which thing you hit you can just do GetComponent<Interactable>().Interact();

#

and not care what the interaction actually does

#

maybe it flicks a light on/off, maybe it activates a rocket ship, whatever, the raycast code doesn't need to know or care.

keen cloud
#

Hm okay would you happen to have a non mono behaviour example as well? I’ve seen them online again but I’m just trying to place where I’d use them in my own code to make things easier

#

Like “to make things easier”

iron fulcrum
#

If I have a reference to a scriptable object, is there a way to get its path inside assets?

sly grove
keen cloud
#

My mind works way too linearly but I’ll try my best lol

sly grove
keen cloud
#

Yes I’m trying to think of that as well but I’ve only used it with co routines

sly grove
#

which is related

iron fulcrum
sly grove
#

this is basically how foreach loops work

#

it works on anything that implements IEnumerable

#

that's why you can foreach on Arrays, Lists, HashSets, Dictionaries, etc...

#

and it's thanks to the magic of interfaces.

#

we know we can call GetEnumerator() on anything that implements the interface because that function is in the interface

keen cloud
#

So literally it’s supposed to be for very broad circumstances

sly grove
#

sorta

keen cloud
#

Hm

sly grove
#

it's for when you want to be able to process disparate objects in a unified way

keen cloud
#

So yeah that’s kinda where my understanding was at but I think I get it more now lol I gotta find places to use it in my code somehow

stoic oar
#

does anyone know how to represent IEEE754 in binary and decimal with c#

#
BitConverter.ToSingle()
GetBytes()
#

i don't understand this function

sly grove
#

"represent IEEE754 in binary" is kinda vague though, that's literally what a float is

#

I guess you want to see the 1s and 0s for yourself right?

stoic oar
#

you have a exemple for get this ?

sly grove
#

Just explained

stoic oar
#

I don't understand how to use this function

sly grove
#

GetBytes to get a byte array.
Then loop through each byte using the link to convert to strings

#

And just concatenate them all together

stoic oar
#

no i am a beginner😅

sly grove
#

You're in the wrong channel

stoic oar
#

yes thanks

stoic oar
thorn cradle
#

Hello,
I do not know if it belong in that channel but I would need help with a crash report.
Would somebody have an idea what could be wrong here? Is it something I can do against it?

#

We are using Ecs. 0.51 with Unity 2021.3.16

ruby gull
#

is it possible you have any disabled objects or invisible colliders in those spaces?

#

Is your terrain generating any grass?

#

try moving your terrain elsewhere and rebaking, see if the spots follow the terrain or stay at that position in the world

knotty sage
#

Hi, I asked about this yesterday in the URP channel but didn't get any bites, maybe this channel's a better place for it -

I'm trying to render a prefab to a texture for use as a thumbnail. I'd rather not add it to the scene to render and I can't see a way of creating, rendering and destroying an isolated secondary scene, so I'm using the Graphics object, a CommandBuffer and a RenderTexture to do this, looping through meshes and sub meshes and calling 'CommandBuffer.DrawMesh' on each sub mesh and material, while setting up the view and perspective matrices manually.

So far so good, it renders the mesh to the texture. However, it's only rendering the diffuse channel - emissive is ignored and there's no lighting. I've tried enabling various keywords and uploading shader uniforms related with lights but these have had no effect - I suspect there's some #def for lighting that I'm missing. I'm also not sure if this is forward rendering, deferred or whatever or how to affect which pipeline is used. I can't find any documentation on this, so a pointer in the right direction would be very appreciated.

#

If it is the deferred pipeline, maybe that's the problem - I'm seeing the diffuse buffer and I need to set up all the other buffers properly and then resolve the lighting in another pass? Or get it to do forward only perhaps.

river sand
#

hey every one i have a script for handling my head bob in my fps system , now i want to know is there any way to have events exactly on the frame when the camera starts and ends the arc movement?

        private void Awake()
        {
            StartPos = transform.localPosition;
            StartRot = transform.localRotation.eulerAngles;
        }

        private void Update()
        {
            if (!Enabled) return;
            
            CheckMotion();
            ResetPos();
            
            if (EnabledRoationMovement)
                transform.localRotation = Quaternion.Lerp(transform.localRotation, Quaternion.Euler(FinalRot), RoationMovementSmooth * Time.deltaTime);
        }
        private void CheckMotion() {
            
            float speed = new Vector3(player.targetVelocity.x, 0, player.targetVelocity.z).magnitude;
            if (speed > 0.1f)
            
                HeadBobMotion();
        }
        private Vector3 HeadBobMotion()
            pos = Vector3.zero;
            pos.y += Mathf.Lerp(pos.y, Mathf.Sin(Time.time * Frequency) * Amount * 1.4f, Smooth * Time.deltaTime);
            pos.x += Mathf.Lerp(pos.x, Mathf.Cos(Time.time * Frequency / 2f) * Amount * 1.6f, Smooth * Time.deltaTime);
            transform.localPosition += pos;
            FinalRot += new Vector3(-pos.x, -pos.y, pos.x) * RoationMovementAmount;
            return pos;
        }

        private void ResetPos() {
            
            if (transform.localPosition == StartPos) return;
            transform.localPosition = Vector3.Lerp(transform.localPosition, StartPos, 1 * Time.deltaTime);
            FinalRot = Vector3.Lerp(FinalRot, StartRot, 1 * Time.deltaTime);
        }
    } ```
ruby gull
stoic oar
#
using System;
                    
public class Program
{
    public static void Main()
    {
        float f = 19.5f;
        var bytes = GetBigEndian(f);
        Console.WriteLine("{0} => {1}", f, BitConverter.ToSingle(bytes,0));
        Console.WriteLine("{0} => {1}", f, GetFloatFromBigEndian(bytes));
    }

    static byte[] GetBigEndian(float v)
    {
        byte[] bytes = BitConverter.GetBytes(v);
        if (BitConverter.IsLittleEndian)
            Array.Reverse(bytes);
        return bytes;
    }

    static float GetFloatFromBigEndian(byte[] bytes)
    {
        if (BitConverter.IsLittleEndian)
            Array.Reverse(bytes); // We have to reverse
        return BitConverter.ToSingle(bytes, 0);
    }
}
knotty sage
stoic oar
#

i try to get it but i don't understand

ruby gull
knotty sage
#

I m sorry to sway off from your question

sand inlet
#

anyone knows the command line arg to build a dedicated linux Server?

sage radish
sand inlet
sand inlet
#

Thx @sage radish

misty walrus
#

Hi, I am trying to implement addressables with remote packages. I have a problem about caching. I want some assets to be locally cached with their latest version. The only method I can think right now is check GetDownloadSizeAsync and if it's bigger than 0, load it. I have a problem and a question about this.
Problem: I really don't need to Load the asset but to rather simply cache it locally, is that not possible?
Question: Since addressable handles unloads itself, if I have to Load the assets and never save a reference to them, will Unity unload the bundle after the method call ends automatically?

finite burrow
#

Is there a way to combine a UploadHandlerFile with the multipart form data?

var webRequest = UnityWebRequest.Post(requestData.url, new List<IMultipartFormSection>() {
            // new MultipartFormFileSection("vanillaZip",await File.ReadAllBytesAsync(tempPath) , "0.0" + ".zip", "application/zip"),
            new MultipartFormDataSection("version", "0.1"),
            new MultipartFormDataSection("bundleHash", "asfasfas")
        });
        webRequest.uploadHandler = new UploadHandlerFile(tempPath);
        webRequest.uploadHandler.contentType = "application/zip";

e.g moving from the FormFileSection to the UploadHandler. The file in this case is large (1-5GB) and the file section won't chunk or stream, requires the entire thing in memory

wooden night
ruby gull
onyx blade
#

I have a function that is calculating the bounds of an object first, and also calculates the distance from its pivot to the left limit and right limit in 2 variables. But the calculation I am doing seems wrong...
I drew some gizmos to see the results. I know the bounds is correct cuz I double checked with manual measurements

   public static Bounds CalculateBounds(this GameObject target)
   {
       var bounds = new Bounds (target.transform.position, Vector3.zero);
       Renderer[] renderers = target.GetComponentsInChildren<Renderer>();
       foreach (Renderer renderer in renderers.Where(x => x.gameObject.activeInHierarchy))
       {
           bounds.Encapsulate(renderer.bounds);
       }
       
       ARManager.Instance.instanceController.sceneRoot.transform.SetPositionAndRotation(parentPosition, parentRotation);
       
       if (target.TryGetComponent<DatabaseReference>(out var reference))
       {
           reference.Bounds = bounds;
           reference.Reference.distanceFromCenterRight = Math.Abs(bounds.max.x - target.transform.position.x);
           reference.Reference.distanceFromCenterLeft =
               Math.Abs(bounds.size.x - reference.Reference.distanceFromCenterRight);
       }

       return bounds;
   }

   void OnDrawGizmosSelected()
   {
       Gizmos.color = Color.red;

       var positionLeft = new Vector3(transform.position.x - reference.distanceFromCenterLeft, transform.position.y,
           transform.position.z);
       var positionRight = new Vector3(transform.position.x + reference.distanceFromCenterRight, transform.position.y,
           transform.position.z);
       Gizmos.DrawSphere(positionLeft, 0.1f);
       Gizmos.DrawSphere(positionRight, 0.1f);
   }
wooden night
#

Holy shit that’s a lot of code for something so simple

#

isn’t there the bounds method? i think it’s under the mesh renderer

onyx blade
#

I honestly wish I didn't have to do that

wooden night
#

idk what those are but damn

#

yea i would too

onyx blade
#

compounded = multiple meshes in one parent. f.e. the black pillar and the glass panel are separate under the same parent, but I need to have the bounding box of them as one object

wooden night
#

you seem to know what you’re doing a lot more then i do, so could i ask you a problem i was having?

onyx blade
#

lol, go ahead

wooden night
wooden night
# onyx blade lol, go ahead

i was making a loading bar right, and i have the width of the loading bar set to LoadingBarObjX but for some reason it reads the width as a negative and i’m trying to make a if statement that checks if the width is bigger then 0 and so i have to check if it’s less then 0

onyx blade
#

yeah, getting their bounds and using encapsulate allows you to get the bounding box of things together. You can use that to get bounding boxes of an entire scene too for example.
(Its very useful to generate a collider for objects that can change at runtime and need adjustments to the colliders

wooden night
#

Interesting

wooden night
#

idk just unitys hi

#

ui

onyx blade
#

ah the gameobject based one?

wooden night
#

yea

#

i think

#

the one where you right click go to ui and choose what you want

onyx blade
#

yeah, you arent working in separate documents that look like html

#

uhm lemme think

wooden night
#

what?

onyx blade
#

dont worry about it

wooden night
#

ok

onyx blade
#

are you using an image?

#

if so, set the image type to filled with fillmode horizontal and origin left/right if needed. then you can set the fill amount to a value between 0 and 1

#

alternatively @wooden night good old brackeys https://www.youtube.com/watch?v=BLfNP4Sc_iA

Let's create a simple health bar using the Unity UI-system!

Get up to 91% OFF yearly Hostinger Plans: https://hostinger.com/brackeys/
Code: "BRACKEYS"

● Brackeys Game Jam: https://itch.io/jam/brackeys-3

● Project Files: https://github.com/Brackeys/Health-Bar

···················································································...

▶ Play video
wooden night
#

alright i’ll try that

#

It’ll be a couple hours though i’m in school rn

onyx blade
#

thats alright, feel free to tag me later if you need help if it doesnt work

proper sparrow
#

I'm making a VR game in unity where you sit on a magic carpet, and I want to be able to grab the corners of my rug, which already are using the cloth component

#

I have tried to attach grabbable cubes on the corner of the rug, but they won't stay

#

and follow the rugs movement

onyx blade
proper sparrow
#

Animation of the mesh

onyx blade
#

that makes sense, since the animation of the mesh will not change the meshes position at all

#

well, unless you have root motion but thats not relevant here

proper sparrow
#

Is it possible to attatch a cube to the cloth animation?

onyx blade
#

I think you can, but the only way I can think you can do that is by getting the vertices of the corners you wanna grab and manually setting the position of the cubes to that vertex's position

proper sparrow
#

But how?

onyx blade
#

you would need to read the meshdata and find the 4 corners

proper sparrow
#

Is that a class?

#

Or how do i acess the meshdata?

proper sparrow
#

Thank u Torben, I'll give it a try

undone coral
finite burrow
undone coral
#

hmm

#

maybe use httpclient then

#

you can also try besthttp/2

#

are you trying to upload something to an s3 bucket?

versed coyote
#

Hm I a using Zenject Signals at the moment.
Just by accident I stumbled over this method here:

https://docs.unity3d.com/ScriptReference/Component.SendMessage.html

I wonder which is performing better? The way I am using Zenject Signals is actually easy to swap with Component.SendMessage. However I'd love to know about any pitfalls with that approach

undone coral
pine anvil
#

How to make the NavMeshAgent not be repelled by the player or player object? (pls ping me)

versed coyote
undone coral
#

it provides no value, it is negative ROI

versed coyote
# undone coral it provides no value, it is negative ROI

Coming from web engineering and using Spring Boot for most of my backend software I am very keen using Dependency Injection. And Zenject really helped me tidy things up and keep out of the Unity Editor for most of the time

versed coyote
undone coral
#

what are your goals? to make a game?

versed coyote
undone coral
#

okay well i think you'll figure it all out

#

i wouldn't use spring boot either

versed coyote
# undone coral i use vertx.

On my first glance I could not see any Unity integration. Zenject allows a nice approach to inject Prefabs and such quite nicely

undone coral
#

i'm saying, when i write a backend application in Java, i use vertx

versed coyote
undone coral
#

in every setting where i've interacted with senior or sophisticated programmers, dependency injection, like annotations, are code smells

#

if i saw zenject used in a unity game, my reaction is "this person is dunning kreugering their way into never delivering a game"

#

keep out of the Unity Editor
use pygame

versed coyote
#

Hm. Well no offense but you did not yet provide any real arguments. You just say that things (DI in this case) is bad. But aren't really explaining why you think that is?

undone coral
#

the substantive argument is "experience" which isn't something you can just write

#

i'm not a content creator, i don't have a youtube video with 5 bullet points about why zenject is bad

#

i can only give you my opinion

#

it's just opinions

#

you should look at vertx for java

versed coyote
undone coral
#

in my experience, the vast majority of dependency injected dependencies only have one implementation, so having the dependency injection framework and all of its attendant flaws and bureaucracy are redundant

#

there aren't "multiple competing vendors" in a unity game. if you "change vendors" you made a mistake

#

you won't gain value from having the DI framework. it will just add more work to something that was going to happen anyway.

#

this is true in spring boot too

versed coyote
undone coral
#

i think the appeal of zenject and DI is that it's a way for people to think and organize code

versed coyote
#

Yeah for me it removed the "manual" labor. I want to write the game and not drag and drop it

undone coral
#

for example, in animation, sometimes you just rotoscope by hand, and it will be faster for even a thousand frames, than dealing with a piece of dedicated software

versed coyote
undone coral
versed coyote
#

While having everything in my codebase it's very easy to navigate thanks to modern IDEs

undone coral
#

is your game Factorio?

#

this is why i asked you what your goals were

#

because it doesn't sound like the goal is to make a game

#

do you see what i mean?

versed coyote
undone coral
#

or at least, what is the specific kind of game you want to make? then i can at least say if your opinions are aligned with that kind of game

#

for example, in medicine, people who find blood and guts icky, there are a few specialities that are really compatible with that. radiology comes to mind.

versed coyote
undone coral
#

well what is maybe a small step towards that goal that you are excited about?

versed coyote
#

is that a question?

undone coral
#

yes*

#

like what would be small step towards achieving that vision

#

that most excites you

#

like many people go into medicine "to help people" which is good, that's kind of the answer "make an MMO"

versed coyote
#

I can't follow you to be fair? You ask for my motivation?

#

Ah ok

undone coral
#

and a small step to that is "become an X"

#

and if you hate blood and guts it makes sense if that is "become a radiologist"

versed coyote
#

Well I am a huge Fan of Wurm Online. I'd like to have a small, loyal playerbase to enjoy the game world I craft. Just like WO does

undone coral
#

this is important for at echnology choice

#

okay... well wurm online

#

i just visited it

#

so like a first step that would make sense to me

#

is "you can build a building inside your unity game"

versed coyote
#

Well don't get me wrong. The project is already in development

undone coral
#

i just feel like that involves a lot of UX... you're going to be touching the editor

versed coyote
#

At the moment the netcode for multiplayer movement is implemented

#

That's my first step here

undone coral
#

hmm

#

i would say maybe focus on like, a simulator for animal behavior

#

something where the result is, essentially, a graph

#

something more Dwarf Fortress

versed coyote
#

Well maybe we just drop out of context here - I already have a full game design in place

undone coral
#

i just want you to thrive

versed coyote
#

If you're interested I can share you a discord link via DM

undone coral
#

sure that sounds nice

versed coyote
undone coral
#

okay i gotta go

#

you'll figure it out

undone coral
# versed coyote It's an MMORPG

Anyway i think the best perspective here is that Unity is a bad choice for MMOs. You can use unreal instead if you need a multiplayer game

#

Unity is a bad choice for many kinds of real-time multiplayer games

#

Unity net code is bad, and the vendor multiplayer frameworks are bad, and that’s why hardly any real-time multiplayer games succeed in Unity

#

If you’re excited about real-time multiplayer don’t use Unity

#

I wish they were more honest about this

opaque swan
versed coyote
#

Also for my project high performing netcode isn't necessary. It's not a competitive MP game

timber flame
#

Can I slice texture atlases like sprite atlas or I have to extract grid data (origin,size) for each slice myself?

//TextureTiles[]
[Serializable]
public TextureTile{
   public Vector2Int Index;
   public Vector2Int Size;
}
midnight venture
#

@undone coral DOCTORpangloss giving health care analogies. well played :D

wooden night
sly grove
wooden night
#

uh

#

what

#

Oh

#

I see

wooden night
#

It looks weird when I put it on filled though

#

Is there anyway to fix my issue without setting a sprite?

sly grove
#

also what's your issue anyway

wooden night
#

I have a loading bar right and the loadingbarobj I have LoadingBarObjX and y set to its size however it reads is size as a negative

#

but it doesn't say it does

wooden night
sly grove
wooden night
sly grove
wooden night
#

That used to be a rectangle

sly grove
#

use a blank white sprite

wooden night
sly grove
#

why

wooden night
#

Its a loading bar

sly grove
#

what are you trying to make

#

a loading bar?

wooden night
#

Yea

sly grove
#

That's a standard filled image

#

no need to change size

wooden night
#

Do you know how loading bars work

sly grove
#

yes

#

very well

#

I've made many

#

Filled image is far superior to messing with UI size in code

wooden night
#

Ok, then you know they move or change in size

#

But that doesn't change the fact it looks weird

sly grove
#

use a blank white square sprite

#

it won't look weird anymore

jolly token
#

This is not code question nor advanced 🤔

wooden night
#

It is a code question

#

Not advanced but

wooden night
sly grove
wooden night
#

its 12 mins

#

When does he talk about that?

sly grove
#

You've been bugging me for longer than 12 minutes

wooden night
#

You dont have to continue talking to me

#

I appreciate the help

#

Oh shit, huh some some sprites do the weird thing and some dont

#

Its just the sprite, I thought I had to do something

burnt egret
#

proud of this particular bit of code i wrote

IEnumerator GetLocalizedText(string key, TMPro.TextMeshProUGUI text)
    {
        var value = dataModel.keyValue.Where(x =>
        {
            //remove white spaces if theye are there
            if (x.name.Contains(' '))
            {
                //may be issue with upper/lowercase
                string temp = "";
                x.name.CopyTo(0, temp.ToCharArray(), 0, x.name.Length);
                ReplaceWhitespace(temp, "");
                return temp.Contains(key);
            }
            return x.name == key;
        }).ToArray()[0].value ?? string.Empty;
        Debug.Assert(value != string.Empty,$"{key} returned no value for GetLocalizedText in IntermediateView!");
        var asyncOperationHandle = LocalizationSettings.StringDatabase.GetLocalizedStringAsync("WaitingRoom", key);
        while (!asyncOperationHandle.IsDone)
            yield return asyncOperationHandle;
        text.text = $"{asyncOperationHandle.Result}: {value}";
    }```
#

it would look a lot nicer if i didnt have to get rid of whitespace but hey its neato

#

and it works so thats pretty cool too

fresh salmon
#

//may be issue with upper/lowercase
If you want case-insensitive comparison, Contains can take a second argument that dictates the comparison type. Pass any of the IgnoreCase options

burnt egret
#

oh neat! thank you

fresh salmon
#

I also don't quite get that array copy operation, if you just need to replace whitespace you can do .Replace(" ", ""), it won't modify the original string, but rather return a new one

burnt egret
#

oh really? i thought for some reason that since strings arent a value type it would edit the original string

#

woopsie

#

you just saved me a bunch of performance thank you ❤️

#

i should also probably make the other case call Contains as well

fresh salmon
#

They aren't a value type you're right, but C# treats them specially, they're immutable. Changing one always creates a new one in memory that contains the new value

burnt egret
#

interesting, thats super cool i didnt know that

#

is there a nicer way to do Where where i dont have to convert it to an array and get the first value?

fresh salmon
#

Sure!

var val = dm.kv.Where(x => x.name.Replace(" ", "").Contains(key, StringComparison.OrdinalIgnoreCase));
#

One liner to rule them all

burnt egret
#

will that return the string im looking for or some weird datastructure?

fresh salmon
#

That returns a collection of string

burnt egret
#

ah okay, yeah i want just the first value of the collection and i was wondering if i could get that without having it create an array

fresh salmon
#

I just saw that you take the first one in that code, so you can replace the Where with a First to get the first matching string directly

burnt egret
#

cause i know there will only be one value

#

oh neaaat okay

#

what im getting from this is that i should go read Linq's documentation lol, thank you so much

fresh salmon
#

Note that with First you will get an exception if no match was found. Use FirstOrDefault, which doesn't throw, but returns null if nothing is found

#

Linq comes with time, you learn something new about it every day. A few days ago I discovered the MinBy and MaxBy methods which are different from Min and Max

#

Oh yeah and if you always expect to have only one match in that list, ever, then you can use Single instead of First, which throws if no result, or more than one matches are found. If it blows up in your face, you have duplicates somewhere!

burnt egret
#

omg, thats awesome

#

alrighty definitely doing that now

#

thank you so much!

#

since i never took a course on C# in university, i cant help but feel like i dont quite have a holistic grasp on the language, i actually joined this server with the intention of fixing that + i feel the same with Unity

brisk pasture
#

assuming you did Java in University, if so you already have a good handle on how C# works. just different names on things

misty glade
#

Is there any way to view/inspect the optimization I'm getting out of Sprite Packer V1/V2?

I'm getting some pushback from my artist who insists on generating sprite sheets versus individual textures, since I was under the impression Unity handles a lot of this packing automatically.

How can I research this? Or find out if it matters/doesn't matter for a bunch of textures we're about to use in our project?

violet comet
#

So whether your artist puts them all into one sheet or multiple or 100, and you pack them all into 1 atlas, it'll be 1 texture and 1 draw call

misty glade
#

Any changes to the file size of the distribution? He's sorta insisting on this extra effort (him packing them into sprite sheets and me unpacking them) and.. I'm positing that it's not really worth the effort right now. A point in his favor, they are relatively large images and there's a lot of them, so optimizations would be nice. They're backgrounds for cutscenes.

#

850x480

#

(and there's probably going to be 20-30 of them)

heady linden
#

Hey,
So the AI Destination is looking for a transform to follow,
https://gyazo.com/694763d14cf26e2f53ea7c5219d80ae4
(player transform)

But i want it to follow the player when its walking into a detection collider,
So i made this script: https://pastebin.com/9TMK0uR3 (which is working and all that)

But, now i need my AI destination to read out a transform from a list, ONLY when its availible,
List: https://gyazo.com/797602d8c82660e3124b6818dc93cec2

Player transform will be added into that list when its walking into the detection collider,
How i can let the destination script read out if something is in that list? and then get THAT as transform to follow when its in the list?
Cus i looked up a lot of stuff, and im kinda lost XD

sterile snow
#

Hmm does it make sense to be using custom attributes to define such things like identification strings with classes? Essentially metadata that never changes and needs to be directly associated with a class, whether an instance of it is created or not.

#

I was pondering just doing that with a static constant though.

heady linden
#

Do i maybe have to add a canWalk bool? And let the enemies define paths always. But only walk them when canWalk (so enemy in range)? Or will that create lagg if i have a lot of enemies? (Dots pathfinding btw)

jolly token
misty glade
jolly token
#

Sprite atlas is for batching benefit, rather than file size

misty glade
#

oh so it doubly doesn't even matter

jolly token
misty glade
#

yeah, tbh I kinda cbf with this right now.. i have a zillion fires and product launch is in a few weeks so.. changing game objects or the way i get textures out of my SOs is just not what I want to be spending time on.. pretty soon AngrySharping is going to come out and put the hammer down

#

here I am, dealing with a sticky technical issue and my artist is like "hey I think we could get some benefits by redoing all of our texture library stuff what do you think"

jolly token
#

Lol yeah manually doing it wouldn't help

#

Just waste of energy

misty glade
#

Maybe slightly off topic for this channel but thought I'd give it a go..

I've recently installed Storage Spaces in windows 11 and getting some pretty shit performance working in Unity. Looks like one of my drives is .. just fucking ancient and was a bad choice for throwing in the pool.

Any idea if I could sniff out what files are tending to thrash when I'm working in unity? I'm wondering if migrating my project files and/or unity to an SSD would help, or if it'll just be less headache to head down to Best Buy and grab a couple new drives and put them in the pool, taking the old one out as soon as the data's been striped over.

#

Nevermind.. looks like I found the culprit. Drive is limping.

umbral brook
#

is there a way to get the class that implements an interface from the interface?

sly grove
#

If you know what class it actually is, you can cast to it directly

umbral brook
#

kk, previously I have simply stored a reference to it but thught maybe there was a simpler way

#

wdym cast to it?

sly grove
#

This isn't an advanced question btw

umbral brook
#

kk

knotty sage
#

I'm doing some work with CommandBuffers to render a thumbnail, had this working yesterday, today something has changed and my functions to set up the lights seem to have no effect.

I get grey lighting like this now.

Altering the global main light colour and direction doesn't do anything - I'm using "MainLightPosition", "_WorldSpaceLightPos0", "_MainLightColor" and "_LightColor0" to attempt to do this, called on the CommandBuffer object before rendering. The diffuse channel is also ignored, this looks like specular only and from the wrong direction.

#

Could this be some state related issue with uninitialized variables or something? I know that's unlikely in C# but the 'Graphics' subsystem seems state based, like OpenGL - perhaps something important is switched off or on depending on something else in the scene, which would explain why it worked one day and not the next (or I've accidently deleted something vital.. can't think what though!)

-edit-

This is all running off a scriptable object and with no scene but if I render an avatar in the scene and then run my thumbnail generator, it works. This suggests it is something stateful that's causing the issue but no idea what of course.

mortal gust
#

Is it possible to auto generate code based out of unity assets (e.g for each asset of a scriptable object type generate some code)?

knotty sage
mortal gust
knotty sage
#

Cool I have it working by a inspector

austere roost
#

At the moment i have a system where i store global game variables (bool, int, string) to keep track of the player progression (if the player visited a particular location, if the player spoke to the npc and reached line 2 etc), to fire off other game events. Whilst this system is working, I would like to optimise it. At the moment i'm using 3 lists (bool, int, string) and i have a lot of duplication of code for adding/deleting/checking these. Is there anyway I can have some form of table that stores a <Key,Type,Value> to essentially have 1 central location? Or maybe someone has a different approach?

dusk vine
#

You can have list of object that would work with all of those

#

Or just string and convert bools and ints when needed

austere roost
#

i tried a list of object but the problem with that is that the value can only be one type (string) and then you have to either convert to an int or to a true/false value. it's very error prone

lucid girder
#

Should work:

List<object> myList = new List<object>();
myList.Add("Test" as object);
myList.Add(true as object);
myList.Add(1234 as object);
        
foreach(var a in myList) {
  Debug.Log(a);
}
austere roost
#

hmmm a custom editor would solve the "error" prone too... cheers

lucid girder
#

oh, and you can use GetType() to get the actual underlying type (string, int, bool etc)

undone coral
#

don't use GetType

#

don't use object

#

i think this is a code smell

#

you should create a class that strongly and clearly describes your game progression

[Serializable]
public class GameProgression {
 public Act1 act1;
 public Act2 act2;
}

[Serializable]
public class Act1 {
  public bool didKillVampire;
  public bool didVisitHouse1;
  ...
}

...
austere roost
#

i think i managed to do it using odin.
'''
[Serializable]
public enum VariableType {
Bool, String, Int
}

[Serializable]
public class GlobalVariable {
[SerializeField] string keyName;
[SerializeField] VariableType variableType;

[ShowIf("variableType", VariableType.String)]
[SerializeField] string stringValue;

[ShowIf("variableType", VariableType.Bool)]
[SerializeField] bool boolValue;

[ShowIf("variableType", VariableType.Int)]
[SerializeField] int intValue;

public GlobalVariable(string newKeyName, VariableType newVariableType, string newStringValue = null, bool newBoolValue = false, int newIntValue = 0) {
    keyName = newKeyName;
    variableType = newVariableType;
    stringValue = newStringValue;
    boolValue = newBoolValue;
    intValue = newIntValue;
}

}

public List<GlobalVariable> GlobalList = new List<GlobalVariable>();
'''

undone coral
#

you shouldn't be doing this in odin

#

you shouldn't be programming via inspectors

#

you don't need any of this. create a strongly typed class that describes your game progression

#

it's much, much, much simpler

#

and error free

austere roost
#

i'm not, it's just a pretty editor for ease of use within the editor, no ?

#

what's wrong with the above code?

lucid girder
#

The point of that was that the underlying type is still the same so you can get the correct typing out again when needed (by different means like casting, gettype, is etc)

undone coral
#

you are programming inside your inspector, because you're naming variables and setting their types in it

#

do you see that?

undone coral
#
[Serializable]
public class GameProgression {
 public Act1 act1;
 public Act2 act2;
}

[Serializable]
public class Act1 {
  public bool didKillVampire;
  public bool didVisitHouse1;
  ...
}

...
austere roost
#

fair enough, i'll try that one

undone coral
#

do you see how this will just work

#

no

#

don't use gamevar

#

create a class that represents your game state

#

focus on this example

#

do you see why this is better?

austere roost
#

ok

undone coral
#

you don't have to create a custom editor for this. it Just Works

#

so it'll look nice in your inspector

#

although there's no reason to edit this in th einspector really

#

if you need to do something like the player killed the vampire

#
void PlayerKilledVampire() {
 GameController.instance.progression.didKillVampire = true;
}

that's it

#

that's all you need to do

#

do you see how much simpler that is?

austere roost
#

i do actually yes

undone coral
#

okay

#

get rid of the list of vars and such

#

don't do things that way

undone coral
austere roost
#

:/ lol sry

dusk vine
#

no don't hardcode your game data 😦

undone coral
undone coral
#

lots of wrong answers out of the gate today

undone coral
#

you can use a component to store the common aspects of the items. attach it to a prefab. then you can prefab-variant that, using it as a base for all your other items

austere roost
#

hold on, i see a flaw in the code above... everytime i want to add a condition, i need to modify the code? that is not at all what i want

undone coral
#

if there's item specific coded behavior, add it as a component

dusk vine
#

I'm smelling a troll

austere roost
#

i want these these "blackboards" to be modifiable on the fly

undone coral
#

you can decide if you want your code to live inside inspector rollouts. if that's what you want, ask #archived-code-general

lucid girder
#

Just saying... even if something is "sub-optimal" it doesn't means it's wrong. Different issues need different solutions, and not everything needs to be super optimalized.

undone coral
#

you can have your code live in .cs files, in 1 line

dusk vine
#

@austere roost You can use generics to simplify the casting

undone coral
#

it's up to you

dusk vine
#

but I'd use gettype

undone coral
#

i mean you do understand* it's just a matter of intellectual honesty

austere roost
#

O_O

undone coral
#

do you know what i mean by program inside the inspector?

#

if you describe something like a "condition" or a sequence of actions that should happen, that aren't animations but are game logic

#

stuff like that. if you put it inside the inspector, you're programming inside the inspector. it's a bad idea

#

a lotta people do this not because it's a good idea, but because it stylistically feels good

austere roost
#

fair enough, thanks for the tip

undone coral
#

i have a feeling you're not going to do what i am saying

#

which is fine. if you want to reinvent variables, you can do that. you're calling them "game variables." and now you ahve to reinvent lists

#

you came here to ask for help in reinventing lists

#

do you see what i mean?

#

and reinventing types

#

you';re like "but my list, it holds bool, it holds string, it holds int"

#

and now a user is saying GetType

austere roost
#

i do have to say one thing... you're forgetting that not all game designers are pro devs... some game designers are exceptionally good at building a strong flow for a game but can't code... for those people, you do need an intuitive system for them

undone coral
#

you traded 1 line of code for what's going to add up to hundreds of lines of reinventing variables and lists

austere roost
#

something like this, solves this

#

that is super intuitive for a non dev

undone coral
undone coral
#

i think it looks horrible

austere roost
#

cool

worldly imp
#

Jesus Christ

undone coral
#

you can embark on this

#

you can do this i'm not stopping you

#

it's bad

#

you're not the first nor last person to do this

austere roost
#

do what exactly?

#

coz i'm getting kinda lost here now

undone coral
undone coral
#

however with artists, it can feel good to be helpful, or to do the ceremony of "prepping" it for the technology... so this is more of an emotional call

dusk vine
#

@austere roost

` public class DataContainer
{
private Dictionary<string, object> gameData;

    public DataContainer()
    {
        gameData = new Dictionary<string, object>();
    }

    public void Add(string key, object o)
    {
        gameData.Add(key, o);
    }

    public T Get<T>(string key)
    {
        return (T) gameData[key];
    }
}

public class GameEvent
{
    public DataContainer myDataContainer;
    public void DoSomething()
    {
        if (myDataContainer.Get<string>("name") == "kevin")
        {
            myDataContainer.Add("TimesMetKevin", 1);
        }
    }
}`
undone coral
#

i don't think it will necessarily take much extra time. you will have to break it apart yourself in unity

mortal gust
knotty sage
#

Does anybody know how to ensure a shader/material is loaded from C# code - this is running in editor, rendering using Graphics and DrawBuffers and the shaders don't seem to go through the 'cyan' loading phase or anything when going through that route.

#

so I need to force them to load

austere roost
mortal gust
undone coral
undone coral
#

macros are mistake. if unreal were written from scratch today, it wouldn't have macros

#

i would at least start with that

undone coral
#

it's also not a super useful point of view and it will lead you astray

#

is your FPS supposed to be overwatch? like is that the idea?

#

@mortal gust truly first person shooter with spellcasters?

upbeat path
undone coral
#

like is that the design space*

#

is the design space the same as the design space of overwatch?

#

or is it the design space of counterstrike

#

counterstrike has like 4 grenades*

#

do you see what i mean?

#

i know what you're looking for

#

just try to answer the questions

#

simple yes or no: your fps, is the goal to have the same variety of things you could possibly design that players do in the game as Overwatch / Team Fortress 2?

#

it also doesn't matter from the point of view of the design space if it's multiplayer.

#

so it sounds like you don't know

#

which is okay

mortal gust
#

Yes, you can do different things.

undone coral
#

so overwatch?

mortal gust
undone coral
#

i think you're probably better off using Unreal to make an FPS. you're better off using Unreal to make a multiplayer FPS. and you're definitely better off using Unreal to make an FPS that also has the design space of overwatch. unity has essentially no robust approach to doing this.

#

there is simply no way to do this in unity.

#

that's why there are zero games that have ever shipped in unity showing such things

undone coral
mortal gust
undone coral
#

what is V rising?

#

you mean this game?

undone coral
#

they probably suffered immensely during development* and their game is probably full of bugs

brave viper
#

Doc you're being overly confrontational here

mortal gust
undone coral
undone coral
mortal gust
undone coral
#

you can see how input system does it with the input actions assets

#

the source is open

#

good luck out there

mortal gust
undone coral
#

i've implemented a "gameplay ability system." macros make sense in the context of unreal engine. i don't think the user should be taking this approach. it's just a really complex thing

#

it sounds like @mortal gust made no decisions about what it is he actually wants to make

#

it sounds like he wants to make editor tooling

#

i didn't ask directly what the goal is

#

maybe i shoul dhave

austere roost
#

He who? Me?

undone coral
#

even these stunlock studios folks, i'm sure they have a pretty big team and a complex backend. i don't know if they use a vendor solution like photon, and how

austere roost
#

The goal is to allow a non dev to essentially do puzzle logic in editor for a point and click adventure game where there's hundreds if not thousands of vars that are essential to shape the game story and progression. Did the player do this? Say this line? Pickup this item? Then this npc will reply with this dialogue... Just a little overview

undone coral
#

there are lots of opinionated content creators with youtube videos

#

it's not really a play along sort of thing

undone coral
#

sometimes people get mad when i ask them what game they're making

#

the XY Problem is like, every QA discord ever

austere roost
#

Why would I get mad? I'll be off from work in a couple hours and I'll be glad to have a discussion about it.

#

I came in here asking for ideas not to contradict anyone 🙂

undone coral
#

well so what's the game

austere roost
#

A mix of monkey island and firewatch

#

Essentially

#

A very story driven "point and click adventure" but from a first person perspective (i know, it stupid calling it a point and click but there's no easier way to describe it)

undone coral
#

i think usually the best way to architect this kind of game is around an Ink script

#

and try to make the script as un-programmery as possible. like write a good script with interesting stuff happening first

#

more like a screenplay than a novel

#

like write the first first day of a firewatch style game*

#

you can also represent actions the player takes using ink options.

#

it already has variables

#

and lists

#

and all this stuff that is useful for representing state. imo you should be using state very very sparingly anyway

#

in a narrative game

#

@austere roost have you seen Ink?

austere roost
#

I have and did use it but it's super annoying to split up the logic, items, characters, locations etc from the dialogue and have an outside tool that has to essentially parse a json...super error prone and it's very hard to debug too.

#

I tried ink, twine etc ..they have the same issue

#

I make heavy use of scriptable objects in my game to store things like item data, character data, locations etc.

#

You want a new item? Just create an SO for it and it's ready to use anywhere

undone coral
#

okay

#

well i'll just say it really depends on what kind of game you want to make

#

there's an asset store kit for lucasarts style point and click adventures and also for first person hidden object game / walking simulators

#

it is very hard for a single person to make something immersive, it takes a lot of production values. super cost effective production values are more serendipity than something you can figure out from first principles. that horror game where you're driving around in a car escaping a giant monster comes to mind - it's serendipitous that vehicles are really well engineered in unity, and it's serendipitous that horror games are generally very dark, and it's serendipitous that it makes sense narratively that it's really foggy, etc. etc.

austere roost
#

Yeah I know about those but let's face it...if I want an opinionated fill in the blanks system, I'd do it myself how I want it not how someone else thought I would want it

undone coral
#

well i personally do not aspire to make asset store assets

austere roost
#

Neither do I haha

undone coral
#

so i basically never create custom editor rollouts

#

and i've been at this for a long time

#

this idea of someone being a non programmer - i mean, that has nothing to do with the kind fo game you're making

#

which should be a signal to you why i don't really want to engage in that

#

i don't think investigating "how to make something a non programmer can use" will lead you to a better or worse game, from first principles

#

nobody knows.

#

and opinions that are just "well wait until you find out the facts" are not opinions at all. you can certainly make an asset store asset that is "The Third or Fourth First Person Walking Simulator Building Tool" meant for someone other than you to use, then observe someone use it, and then be like, "oh i was right" or "oh i was wrong" but you will have still made no games

#

ink has been used in a lot of games

#

i like it because when i work with writers, who don't program

#

like hwy would a good writer want to open up unity?

#

a good writer never wants to open up unity

#

they like ink. it looks like a screenplay

#

it doesn't have nodes and lines. why are there nodes and lines dialogue editing tools?

#

why do so many games have terrible narratives? good questions.

#

it sounds like you want to make firewatch. firewatch, i'm sure, had a script

#

something that looked like a movie script. it is a linear game

#

they also had olly moss, maybe one of the most famous living pop art designers

#

so of course it didn't have to be dark. and the art* could be made by 1 person because it was a good looking non photoreal style

#

and i'm sure it still cost like $1m to make

#

campo santo is owned by valve now, but it's a big studio

#

it wasn't* made by 1 person. COULD it? maybe. so many serendipitous things

sterile snow
#

I noticed some discussion about "splitting up logic from the dialogue" and to be perfectly honest with you, you kind of have to (to some extent) if you want to make easily writeable and re-writeable dialogue

#

No one should ever have to open up source code to prod into strings like that

burnt egret
#

The less code you have to write, the better imo, so why bother with a thing you can't edit through the editor unless you have to, that's how I make games anyway

undone coral
#

i think the number of people on this planet who are both great writers and aspire to write for video games and not movies or books is very very small. it's kind of a moot point. in my opinion, if you're a single person, try to give the person who is making the narrative a tool that looks the most like Final Draft.

#

because there are way more people who are great writers who aspire to write screenplays

#

so they will at least know what to do

sterile snow
#

I personally am making a text adventure game because I'm both a writer and someone that specifically wants a fully interactive narrative game, and what I do is make every piece of dialogue accessible through many JSON files with a strict key naming scheme

#

Since most things are flavor text anyway this works well for me at least

#

And I can just drop new things into the JSON file and it'll work in a snap

burnt egret
#

I think if/when I start writing a story for a game, I'm gonna use yarn spinner

undone coral
sterile snow
#

May I ask what ink does?

#

I have something working right now but I'm open to new things to try to improve my workflow

austere roost
#

I think you're completely missing the point. Whilst I might not be as experienced as you, your perfect view of how things should be done is blinding you to many things and are assuming a lot. There are people who aren't devs. They're story tellers but have the ability to understand what a variable is. If I can pass a tool in editor that someone can iterate over different options for a puzzle without 1) learning how to write for ink or twine or w/e (which if you have used them, they're not as straight forward...it easy to mess everything up with a typo for example), 2) fast iteration, 3) they don't have to run to the dev to do something.

undone coral
#

it looks like a screenplay. it's a way to author dialogue and other screenplay-similar things for a game, where scenes can branch.

undone coral
#

just in my experience, "storyteller" is a flimsy thing

austere roost
#

Then you can also understand that the PERFECT solution, doesn't exist.

#

Because every situation requires a different solution

burnt egret
#

I will say, there's a reason why tool programmers exist, it depends on the scope of your project but anything that simplifies development is gonna greatly reduce the time it takes to make the game

sterile snow
#

I dunno if any of this helps with the convo but it's what I do.

austere roost
undone coral
#

since that's my goal

#

not stuff that lets you make any game

burnt egret
undone coral
austere roost
undone coral
#

and it works well

#

ink is nice because you can test it right away

sterile snow
#

Ahh

undone coral
#

it already has a working little thing that lets you play through your screenplay

sterile snow
undone coral
#

it's just a little creativity around how to choose options

#

that lets you do a "write a verb" style game that's backed by an ink script

#

but "write a verb" is still fundamentally making choices

#

and tbh, if you ever want it to work on phones, well no one is going to type verbs

austere roost
#

I did like both ink and yarn spinner but they all have the same issue. You write outside of unity in their language. You deviate a little bit and json doesn't compile.

#

They're brittle

#

Especially if you send the files to translation services

burnt egret
#

Yarn spinner has its own very simple programming language and I believe you can put event hooks into your story script

austere roost
#

Like they care to use a tilde instead of a dash

burnt egret
#

But idk never used it in production so

undone coral
#

i've sent my ink scripts to professional translators and they haven't really had any issues

#

in fact she liked that she could test the thing

#

right in the ink editor, which is just a text editor

#

then again i had a really good translator

#

it wasn't a service

austere roost
#

Well not every translation service is made the same hehe

#

Most just hire part time speakers that they send your file to and have no idea what it's for, let alone how or what unity is

undone coral
austere roost
#

Then you spend an eternity fixing the ink file just that it compiles properly

undone coral
#

anyway

austere roost
#

Anyway, gotta get back to work...thanks for the discussion:)

undone coral
#

you can try the game - https://monstermatch.hiddenswitch.com - this was built around ink

MonsterMatch

Can you beat the algorithm at finding love? This is a video game that advocates for digital inclusion in online dating apps like Tinder.

austere roost
#

Will do..cheers. catch you later

mortal gust
remote drift
#

Does Unity Test Runner support expected exceptions?

sage radish
jolly token
flint geyser
#

So my state machine has 2 behaviours for movement, one for player and one for mobs. Both inherit from IBehaviour and both use IMover to actually produce movement. How would I refactor them into decorators for another behaviour?
Why decorators instead of inheritance? Because my system isn't inheritance-friendly

hardy nymph
#

Hi I use this code to make a list of components and convert it into JSON form:

static List<string> getComponents (GameObject gameObject) {
    Component [] components = gameObject.GetComponents (typeof (Component));
    List<string> componentsList = new List<string> ();

    for (int i = 0; i < components.Length; i++) {
        string json = EditorJsonUtility.ToJson (components[i]);
        componentsList.Add (json);
    }

    return componentsList;
}```
#

It's working fine but I want to ignore the private fields in it

#

How can I make it ignore private fields ?

sly grove
#

Why are you using EditorJsonUtility?

#

Just regular JSONUtility

hardy nymph
#

It's an Editor script, it runs while the game is not running.

sly grove
#

That's ok

#

Use the regular JSONUtility

#

If will ignore private

#

Unless serialized

modest lintel
#

EditorJsonUtility serializes the actual component data, which is pretty cool

hardy nymph
#

ArgumentException: JsonUtility.ToJson does not support engine types.

sly grove
#

Wait you're trying to directly serialize components? Why?

#

What's the goal

hardy nymph
#

Originally I wanted to send the object + component data to the web. On the web I have an interface for editing them in real-time:

#

Previously I was converting entire component data into JSON and displaying that on the web (including the private fields), when changes were made it sent the updates JSON data and Unity duplicated / created a component from it.
Now I want to display only public fields.

modest lintel
#

Could be alternate approaches, but via reflection you could get all the public fields and find the intersection of those and the fields present in the json

hardy nymph
#

I don't know about reflection, where can I learn about it ?

livid dawn
#

How would I rotate an object to match the normal of the surface beneath it? I'm trying to build a spider that can walk on walls. When it walks onto a surface with a different angle than it, I want the body to reorient to have up be the normal of that surface. I know I can get the normal with a raycast, I just don't know how to construct a quaternion based on that.

west scarab
#

transform.up = normal

sage radish
livid dawn
#

That's fantastic, thank you.

west scarab
# livid dawn That's fantastic, thank you.

If you only want to create a rotation from a direction, you can also use Quaternion.LookRotation, which as an overload for specifying both the "up" and "forwards" vectors

#

Up in that case would be your normal, with forwards probably being the spider's transform.forwards I would guess

regal glade
#

I'm working on a compute shader voxel raycaster and for some reason when I pump up the voxel count the Unity Editor craps itself. It runs just fine in a build but in the editor it runs at 1 fps. I know this is kind of a shot in the dark but what could possibly becausing this?? I was showing all the voxels in an array in the inspector but i used HideInInspector to get rid of it now, and I don't have any other large arrays or anything being displayed there.

#

project is basically empty, only 4 objects in the hierarchy in total

#

no debug logs either

#

oh... now it stopped running poorly??

#

restarted and now it runs poorly again. what

#

maybe HideInInspector isn't enough?? guess it needs to be not serialized

#

yeah that was it thanks bros

humble onyx
undone coral
#

can i author a roslyn analyzer right inside unity? how?

ancient talon
jolly token
hollow veldt
#

Was NativeList renamed? I can't seem to find it in Unity.Collections

dire solar
hollow veldt
#

I've just done that but I don't see it still. I'll try regenerating the solution...

#

IMO NativeList should be a part of Unity.Collections

dire solar
#

I agree! Also, if you're using assembly definitions, make sure you have Unity.Collections asmdef included

hollow veldt
#

💯 regenerating the project files worked

#

thanks!

blazing verge
#

Is there a way to switch between urp and hdrp at runtime?

regal glade
dire solar
#

I'm currently using IJob to compute the minimum value from a given NativeArray<int>. Is there a way to speed it up? I tried IJobParallelFor but had race condition issues.

Edit: Solved using IJobParallelForBatch

scenic forge
#

What's the scale?

dire solar
# scenic forge What's the scale?

1+million values. I'm experimenting with two jobs (IJobParallelForBatch + min/max queue) followed by (IJob + min/max singular value that iterates over the queue). This is much faster (and works!) than a singular IJob, so thats cool

scenic forge
#

You could look into splitting the workload into multiple chunks and have each thread deal with one, then a final min for results from all threads.

dire solar
#

Precisely, IJobParallelForBatch came in clutch.

scenic forge
#

If possible, process them while they are produced might also be good, especially if the producer is already using multithreaded jobs.

west scarab
#

If you want it to be even faster you could try reinterpreting your NativeArray<int> to NativeArray<int4> so the burst compiler can better parallelize the instructions. It might already be doing it though, depending on how you wrote it

#

(you'd have to check the generated burst assemblies)

icy aspen
#

Can someone please explain how this is possible?
As you can see, I have two time stamps (one in the active ghost and one in the ghostrecorder component)
When I set the activeghost timestamp (timestamp is a list by the way) to the ghostrecorder timestamp, and clear the ghostrecorder timestamp, the activetimestamp somehow is also cleared

fresh salmon
#

Because the time stamp is a reference type.
From the usage it would be a List<T>.

fresh salmon
#

The variables point to the same place in memory. If you modify the first one, the second will have the modifications.

#

Passing them around with = does not make copies of them

icy aspen
#

ohh

#

that makes sense

#

so, how should i make a copy of it then

#

because that's what i want to do pretty much

fresh salmon
#

First things first, is it a List?