#archived-code-advanced

1 messages ยท Page 170 of 1

sly grove
#

it goes:
field initializer -> deserialization -> Awake -> OnEnable -> Start

regal olive
#

field initializer?

sly grove
#

the thing you have

regal olive
#

num1?

sly grove
#

that sets num1 to 10

#

that's a field initializer

regal olive
#

ohhh

#

so num2 is created and later on asgined on start?

sly grove
#

it's created with the default value for its type, which for an int is 0, and then when start runs it is assigned to 31

ancient talon
#

never felt like I have to elevate my problem here. I am having issue regarding Texture2DArray not properly showing up in Graphics.Blit. When I call Graphics.Blit(source, rt ); as a single texture2d layer, it works, but for some reason using Texture2DArray in source shows up grey (128/128/128 value). To me, tells me that A) Texture2DArray isn't compiling the texture2D I've append using Graphics.CopyTexture method, or B) Graphics.Blit isn't recognizing it as a layers of Texture2DArray, and showing me 0th layer (or null).

Has anyone came across dealing with Texture2DArray and Graphics.Blit?

#

The other options I have in mind is that I was just going to use regular Texture2D and load them one by one into texture slots of a custom shader.

#

I guess I need to ask this question, How can I test Texture2DArray and see if there's any texture stored in it's array?

hallow turtle
#

anyone know in java how u get the whole string when u enter something?

#

like if i wanted bob john

#
            customer.Name = input.next();```
round pawn
#

Hey, in this script https://pastebin.com/mDVks281 I check a box area to determine if a room can fit, but for some reason I can't figure out, the check center is occasionally (important distinction) in the wrong place when the previous room is rotated. Here's a screenshot to help. The green lines are where the center of the box check is and the red line is between the generating node and the center of the box check.

#

You can see that the hall at the bottom right does a check in the correct position in the room with the lamp, but the other side of the hall placed the check 90 degrees from the desired center. I just have no clue why after hours of fiddling

civic talon
hallow turtle
#

the issue is im doing like

#

1 menu option after another

#

this doesnt work

civic talon
#

It's been several years since I've last written in Java... let me play around with it on my end.

hallow turtle
#

i think i fixed it

#

the scanner stuff is annoying

civic talon
#

yup

hallow turtle
#

i think i needed to clear the buffer everytime

#

ah nope hrm

#

ill keep trying

ancient talon
# hallow turtle

This doesn't look like a Unity specific code. Are you asking us to help you with your Java problems now?

civic talon
#

My assumption is that they may be trying to write something for Android specifically. That is curious though because I would expect Unity to already have wrappers around text-based user input.

ancient talon
#

Yes it does. Use normal UGUI.

#

TextInput on android will literally bring up the keyboard on android devices.

sleek gulch
#

When working with IMGUI, I used to be able to create styles based on built-in editor styles (e.g., var newStyle = new GUIStyle(EditorStyles.helpBox)) and then name my new style, and the new style would have the same background image as the original. This no longer works.

Since (I'm guessing) Unity 2019.1 and the introduction of UI Elements, the GUIStyle.normal.background texture seems to always be null in built-in editor styles. According to this post (https://answers.unity.com/questions/1744845/cant-change-button-guistyle-background.html), it seems like the background image may be provided by some USS file and the built-in style name is used to access it the texture. So when I now copy/clone a built-in style and then change the name of the copy, the background image is no longer used by the new style.

Is there any way I can get access to the Texture objects used by built-in editor styles so that I can manually apply them to my custom GUIStyle instances?

hallow elk
#

Hey all. Asking this one again as it's causing some problems with renaming and optimizing scripts.

#

Because of this, when something is renamed, it breaks every reference to the script everywhere in the project

#

Even when it should be renaming it including in the meta files

sleek gulch
# hallow elk Hey all. Asking this one again as it's causing some problems with renaming and o...

I use Rider, and I haven't had any issues renaming MonoBehaviour scripts in the IDE, as it renames the meta file at the same time and Unity recognizes the name change. It's been a while since I used Visual Studio with Unity, but I thought there was a way to enable the parsing of Unity assets even for large projects, but I can't recall details. It was in the Unity extension settings, IIRC.

Without having an IDE correctly handle the renaming of component class files, the recommendation is to rename them inside of the Unity editor so that references do not break.

ancient talon
#

@austere jewel I watch both video about async/await operations and unitask. But now I still succumb to this incredible performance hit. any idea how I could force the async calls to a different thread?

austere jewel
#

UniTask is not about threading operations. It's practically an allocation-free task-based replacement for coroutines. If you want Tasks on another thread you need to thread them with Task.Run, or if using UniTask it has methods to transition to another thread, though it's not ideal

tough tulip
hallow elk
sleek gulch
ancient talon
tough tulip
ancient talon
#

AssetBundle..

tough tulip
#

how are you loading your bundle?

ancient talon
#

LoadAssetAsync<> from a directory first

#

Using async operation here, which is nice, but still... the performance I'm getting hit hard has to do with the texture manuplation after loading the texture in.

tough tulip
#

what kind of texture manipulation?
Set Pixel + Apply?

ancient talon
#

Combine stuff into texture2d array, run through material, call graphics blit, then asyncgpureadback.. finally saving to storage.

#

tex2Darray using graphics.copytexture function.

#

I might have to yield in some part of the code...

tough tulip
ancient talon
#

I was originally using the job system to literally read pixel by pixel and then saving that to the result.

#

seems like using the shader is much faster than the job system.

#

Seems like I've hit unity's bottomneck here.

compact ingot
ancient talon
#

I guess the question I have is this, when loading texture from asset bundle, is the texture already instantiated to the gpu memory?

#

I could save the performance by relying on using pointers instead of handling texture2d around..

tough tulip
#

Texture is uploaded to gpu only when it needs to be rendered

ancient talon
#

I've reached to the most optimal code by far and still can't squeeze down that performance block.. Thanks malloc!

compact ingot
ancient talon
#

Might just get away without encoding to png, and save it as .t2d extension..

undone coral
#

is it possible for a local file system package A to reference local filesystem package B ?

#

right now it does not appear that Unity resolves those packages recursively

#

okay

#

now that i figured that out

#

why aren't assemblies in local package B visible to A when A references B as a dependency correctly?

#

nevermind

#

i figured it all out

ancient talon
#

Is it possible that I could use the UniTask to wait until next frame if the current frame exceeds over certain time intervals?

#

E.g. if current frame exceeds more than 100ms, await nextframe()

compact ingot
#
var sw = Stopwatch.StartNew();
foreach (var item in work) {
    item.Do();
    if (sw.Elapsed > threshold)
    {
        await UniTask.NextFrame();
        sw.Restart();
    }
}
#

but that stuff should actually not be done in tasks but rather in jobs

ancient talon
#

can't. Most of the stuff needs reference, and can't do it multi-thread due to unity's api texture/gpu calls.

compact ingot
#

can't is just a lack of willpower ๐Ÿ˜‰

ancient talon
#

can't, in this case, is a limitation I have from Unity's api.

#

I can do it, if it was thread-safe.

compact ingot
ancient talon
compact ingot
#

too bad

ancient talon
#

Might have to hack around by using Time.time and set that on every child object that's running async operation.

cedar ledge
#

IsObjectMonoBehaviour can only be called from the main thread

#

any help is appreciated

undone coral
#

is there a way to completely remove Input so that i can see everywhere in code where it is used?

cedar ledge
#

ctrl+f or h?

#

that'll let you find where it's used

#

you can't just remove the existence of a class as far as i know

austere jewel
cedar ledge
#

even smarter lol

undone coral
#

from usin git

#

so that when they pull this project and write new code

#

it will show as a compile error

cedar ledge
#

is it because you want to use the new input system?

austere jewel
#

You cannot do that sadly.

ancient talon
#

Sounds like you want to build a .dll library

#

only you can build the .dll and cannot be modify by other developers?

austere jewel
#

It would be nice if the legacy input system was a module that you could just remove

#

but sadly it doesn't seem to be listed as a module

cedar ledge
#
public static class ClassNuker()
{
  [InitializeOnLoad]
  private static Fire()
  {
    NukeClass(typeof(Input));
  }
  public static NukeClass(Type target)
  {
    // ???
  }
}

how 2 complete???

undone coral
#

that's what i thought

#

it's okay it took me just a few minutes to port over

#

i really wish old Input would die

cedar ledge
#

where is class CSharpCodeDegenerator???

undone coral
#

i don't understand how people can be doing this for years, in 2022, and still use Input.touches and Input.GetMouse... with switching for mobile and all this bullshit

ancient talon
#

that's for aspnetcore...

undone coral
#

even the unity docs say Mouse.current instead of Pointer.current

ancient talon
#

Why are you poking around asp.net stuff when you should be looking into .NET for unity? @cedar ledge

cedar ledge
#

sorry it was a bad joke and i wasnt paying attention

cedar ledge
ancient talon
#

really wish there's a way I could break code down based on current frame time since the beginning of frame.

#

Oh and Time.time did not help.

sly grove
#

You can use DateTime.Now.Ticks

final steeple
#

You should prefer UtcNow, not Now

#

Now is an expensive property

#

DateTime.Now can also throw an exception if your system has broken time settings

supple crest
#

I ran some performance benchmarks, and it seems that iterating over a dictionary with its keys is more performant than iterating over a list... why would this be?

final steeple
#

You need to show the benchmarks

#

Otherwise there isn't much to discuss

supple crest
#

Oh, nvm I mislabeled my test... had it backwards

#

good. Perfectly sensible.

cedar ledge
#

what's the Task equivalent of creating a new thread and starting it without waiting to it to finish?

#

just fire and forget

cedar ledge
#

I get a warning saying that I'm not awaiting it

#

Also, I thought that was for CPU-bound methods. I'm doing an infinite loop of listening to a network socket

sly grove
cedar ledge
#

So if I don't intend to use that, just use _ = ?

sly grove
#

sure

#

_ = Task.Run(...);

#

but that might bring the warning back

#

idk

cedar ledge
#

so Task.Run isn't just for cpu-bound methods, then?

sly grove
#

So the thing is

#

In Unity

#

I don't think the threadpool it gives you is a real background threadpool

#

Like it would be in normal .NET

#

I think it might actually run your code on the main thread anyway

cedar ledge
#

I'm converting a whole bunch of thread code to task code so I'm learning

sly grove
#

But in general, it doesn't matter what kind of code it is - Task.Run is fire and forget. The returned Task object is what lets you not forget if you want to not forget

cedar ledge
#

should I configureawait(false) on that?

compact ingot
final steeple
#

The thread pool exists in Unity just as it does in real .NET

#

It's the same implementation

#

ConfigureAwait(false) is only necessary if the thread that the continuation runs on is important

#
// we're on the main thread here
await SomeAsyncMethod(); // this might run on a background thread
// this code is back on the main thread
#
// we're on the main thread here
await SomeAsyncMethod().ConfigureAwait(false); // this might run on a background thread
// we might be on a background thread here
#

So ConfigureAwait(false) should not be used if you call Unity API methods after the await

iron fulcrum
#

Does anyone know anyway to get a random palette from something like coloors.co using an api?

final steeple
#

You would need to see if Coolors provides an API itself

iron fulcrum
#

ah

#

it doesn't seem to

final steeple
#

Does Coolors do anything special to generate a palette that couldn't just be done manually?

#

Should be pretty simple to generate 256 random colors

sly grove
grave fossil
#

Teach me senpais, how to make scriptable object which can save a list of items. The hook is that depending on scriptable object options, the list could hold either int or string or bool or what ever. I searched for hours now, tried generic classes approach and etc. To level where I am thinking to make just 4 scriptable object scripts for different types. But I really want to learn how to make it in correct way....

string scriptbatbleObjectType = "string";
struct MyStruct {
  string name;
  TypeThatCanBeString,IntOrBool data;
}
List <MyStruct> = new List<MyStruct>();
novel meteor
#

I am looking to convert a list to "layers" so i can place objects on top of a perlin noise map.

How would i go about this?

Layer1 would be tileset.Add(0, prefab_plains);
Layer2 would go on top of that, like a tree or random object but me not smart

https://pastebin.com/xnbsYSSw

misty crescent
#

Is brotli compression not working for anybody else? For WebGL builds? MacOS 12.0 (Monterey)
I don't get my build with the .br extension

lucid girder
grave fossil
lucid girder
#

yeah, you'll have to do list<MyStruct<int>>

#

etc

sly grove
#

A couple nasty solutions:

  • use an object field
  • Use multiple fields and an enum field to tell you which one is populated
lucid girder
#

you could use dynamic as well, if it can change during runtime

#

and use reflection to find the type

sly grove
#

Dynamic is pretty much not useful in Unity, as IL2CPP doesn't support it

lucid girder
#

true

sly grove
#

Also probably slower than the enum method ๐Ÿ˜†

lucid girder
#

yeah, it will do runtime checks constantly instead of during compile time

grave fossil
#

Well just created Custom variable with all possible strings. and will just show correct GUI depending on type with UI toolkit....

silk canyon
#

Has anyone done parallax UI on a procamera 2d before? I can't render button UI by using the camera of the layer I'm interested in.

grave fossil
lucid girder
#

yeah, though you could write a custom inspector for it

grave fossil
#

Yea, but in the end I would need to write multiple Editors for each type. Sio it kinda destroys Idea of unifying it ๐Ÿ˜ฆ

lucid girder
#

you could simply show a string of the value, everything should have a ToString method iirc

#

atleast, if you don't need to change the values in the inspector

final steeple
grave fossil
#

2021.2.9 My editor refuses to agree with that statment ๐Ÿ˜„ at least in list ๐Ÿ˜„ it shows same way as if list would be from Objects

flint sage
#

It works differently, you have to use SerializeReference and probably make a custom propertydrawer for them

grave fossil
#
public class BoolButtonSciptableObject : ScriptableObject
{
        [SerializeField] public List<CustomButtonClass<bool>> m_ButtonsList;
}
[System.Serializable]
public class CustomButtonClass<T>
{
        string title;
        T value;
}
bitter crane
#

Hi

bold mountain
#

hey everybody! How is it possible to get a type mismatch with FindObjectOfType...?

lucid girder
#

what do you mean type mismatch?

bold mountain
#

well um, couldn't be clearer, when my fields are hydrated by my findObjectOfType, there is "type mismatch" written inside them

#

and i did some debugging, but my objects are indeed the ones i want them to be, but...

#

here's my whole script

#

(ignore my intern monologue in comments)

#

and when i click "hydrate":

cedar ledge
#

I have an event OnNetworkTick that needs to be invoked repeatedly. Currently, I'm using another method StartNetworkTick to handle the infinite loop. The problem I'm having right now is that it doesn't stop when I exit playmode. I think it also should run on the main thread due to unity limitations. How can I fix this? Is there a better way to set up an asynchronous infinite loop?

// ServerStart():
// Task.Run uses a threadpool, not main thread
_ = Task.Run(() => StartNetworkTick());

// event
public delegate void NetworkTickEvent();
public static event NetworkTickEvent? OnNetworkTickEvent;
// loop
private async Task StartNetworkTick()
{
    while(true)
    {
        OnNetworkTickEvent?.Invoke();
                // accessing singleton might need to be done on main thread?
        await Task.Delay(NetworkCore.Instance.NetworkSettings.TickDelay); 
    }
}
bold mountain
#

i need to add a getComponent, that's it?
ok i'm dumb, thanks everybody bye lol

bitter crane
#

I have a player in resources folder how can I get it value with script instead of using inspector

bitter crane
#

Thanks

bold mountain
#

ok nvm update: still having types missmatchs,
But when i try to debug.log values within the scripts themselves, well... it works like a charm.
I'm going to be using it like that, but i'm worried this might blow up on me at some point

cedar ledge
#

an asset can't reference gameobjects in the scene

cedar ledge
#

not an instance of those prefabs in the scene

bold mountain
#

ok so i'm trying to use dark magic basically?

cedar ledge
#

no

#

you're trying to have an asset reference the scene

bold mountain
#

that's a shame
Honestly i'm not trying to overuse this. Basically, i have a list of scenarios, and i'll be using this to add scenarios with a simple button, instead of a click and drag.

#

(my tool is aiming towards non-devs)

cedar ledge
#

are the managers prefabs?

bold mountain
#

nope

cedar ledge
#

why not?

bold mountain
#

they might be sometime in the future though, yeah

#

but haven't done that part yet

bitter crane
#

I have a player how can I give value of player to var with just script and without inspector

cedar ledge
#

well you could go ahead and do that and have your button load the prefabs instead

bitter crane
#

No it's advanced but what I mean is that I want the value of the instantiated player which is over the photon network

bold mountain
bold mountain
cedar ledge
bold mountain
#

be precise :)

cedar ledge
#

what is "value of the instantiated player"

#

a reference? an id?

bitter crane
#

Ok let me explain just a min

#

So let make it clear what issue I have is that I want my camera to follow the player which is over the network i just want to give a value with script i dont want it to be done with inspector

cedar ledge
#

what value?!

#

the position of the player?

#

what do you mean the player is "over the network"? the gameobject exists locally and is synced over the network

bitter crane
#

Over photon network

#

Which uses the internet

cedar ledge
#

i can't help you if you don't be precise with your question

bold mountain
#

you might want to try on the Photon Network discord server / forums for this question, maybe.

bitter crane
#

Ok so any so just tell me that how do I get the camera follow the player without drag and drop

cedar ledge
#

so you want to find the player gameobject from a script? FindObjectOfType<Player>()? This is a really beginner question. Maybe move to #๐Ÿ’ปโ”ƒcode-beginner

bitter crane
#

Ok but the player is in resources folder but thanks

cedar ledge
#

why didnt you bother mentioning that?

#

like, at all?

#

var player = Resources.Load<Player>("Prefabs/MyPlayerPrefab");

bitter crane
#

Thanks but that is not working for me

cedar ledge
#

feel free to elaborate on that

bitter crane
#

Ok

#

Thanks

cedar ledge
#

alrighty then

bitter crane
#

But where are you from

cedar ledge
#

i live in your walls

bitter crane
#

Oh ๐Ÿคฃ

#

I was asking about country not your address of home ๐Ÿ™‚

cedar ledge
#

If you go to the middle of the Indian Ocean and dig really deep, you might pop out somewhere nearby me

bitter crane
#

Ok i am on my way to your home ๐Ÿ˜

cedar ledge
#

malloc about to drop a thesis of a question

tough tulip
bitter crane
#

Just landing

bitter crane
#

And yeah I am landing on your House terrace

#

Just kidding ๐Ÿ˜‚

remote drift
#

Anyone knows in async operations (UniTask in my case)
when cancellation token get called, does it discard everything that goes after Yield in method?

#
    private async UniTaskVoid FlipAsync(float duration, CancellationToken cancellationToken)
    {
        var endTime = Time.time + duration;
        float angle = transform.rotation.eulerAngles.z;
        float counter = 0f;
        bool didAnimation = true;
        while (Time.time < endTime)
        {
            counter += Time.deltaTime / duration;
            float step = (counter < 0.5f) ? counter : Mathf.SmoothStep(0.5f, 1f, counter);
            if (didAnimation && counter > 0.80f)
            {
                animator.Play("PostFlip");
                didAnimation = false;
            }
            transform.rotation = Quaternion.Euler(0, 0, Mathf.Lerp(angle, VelocityRotation.eulerAngles.z - Mathf.Lerp(0f, 360f, counter), step));
            await UniTask.Yield(cancellationToken);
        }
        shouldRotate = true;
    }

Here code I have and I experience troubles that this little piece of shouldRotate = true is not getting executed if token is cancelled

flint sage
#

Well yeah, the method never gets continued

#

So that yield is the last line that executes

remote drift
#

is there a way to ensure callback?

flint sage
#

Idk how UniTask works

#

You can try using try/finally

remote drift
#

it's just async operation tied into unity ecosystem

lyric dew
#

hi guys.
Can unity take several image files and put them together for me into a spritesheet or tileset? I seem to have trouble getting my assets into the project as single images, all the tutorials are using tilesets

flint sage
#

Sprite Atlas?

lyric dew
#

i thought that as much but when i click "pack preview" I see nothing there

untold moth
# lyric dew

Try dropping in the actual images instead of a folder.

lyric dew
#

i'll load up my project again and give that a shot

lyric dew
#

well it said it packs it but it doesnt show a preview

remote drift
# lyric dew

preview is in scalable window. You need to expand to actually see preview.
Even if it's empty it'll be just empty texture.

lyric dew
#

ohh man i feel dumb as hell. so it's minimized you have to click drag from the bottom up to see the preview. lol

bold mountain
#

Hi! anyone know why i need to recompile my code to get this executed? i was hoping it launches when i launched my project, but it's not

cedar ledge
#

InitializeOnLoadAttribute allows you to initialize an Editor class when Unity loads and when your scripts are recompiled.

bold mountain
#

So, wdym when unity loads?

#

when i launch the project?

compact ingot
bold mountain
#

here? Just activated it

compact ingot
bold mountain
#

but it says "enter playmode"...

#

i'm talking about when i open my project

#

do i really have to screencast this to explain it? ๐Ÿ˜ญ

compact ingot
#

no I get it

cedar ledge
#

no i understand it

bold mountain
#

thank you ๐Ÿ˜ญ

cedar ledge
#

that might do the trick though

bold mountain
#

nope! it's not

cedar ledge
#

Static constructors with this attribute are called when scripts in the project are recompiled (also known as a Domain Reload).

compact ingot
cedar ledge
#

yeah

#

so it's not reloading the domain on startup

bold mountain
#

okok i'll try some things, but really it's weird

bold mountain
remote drift
#

wait a second, do static constructors load after each domain reload?
Without attributes

#

or only on play?

cedar ledge
#

what if you do [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]?

compact ingot
#

those attributes will not run if their underlying trigger does not fire

cedar ledge
bold mountain
#

still not working :/

#

but if i may
I have automatic domain reload unactive, cuz i prefer reloading manually
BUT
When i launch my project, i "can't" reload manually, cuz there's no changes made in my domain. So hitting ctrl+r doesn't even execute the methods if nothing has changed.

gilded wing
#

sort of a general C# question ... i thought i was being clever by making a class that contains an array of delegates that it runs in sequence according to instructions as an alternative to a certain type of unity coroutine i was using a lot, and it does work great except the stack trace in the debug log messages is near useless because it's showing only the container class internal methods instead of what the delegates are actually set to - there's probably nothing i can do to fix that, right?

#

like that's just how delegates work, i figure

#

tried setting the stack trace log type to full but it's the same thing, not that kind of problem

final steeple
#
Action d = Function1;
d += Function2;
d(); // calls Function1, then Function2
gilded wing
#

oh it's meant to run in update, like calling the container's update invokes its "current delegate" which return an instruction whether to repeat itself or to move to the next one, like a sort of very simple linear state machine i guess

final steeple
#

Ah I see

#

So you only want the next one to execute if the previous one succeeds

gilded wing
#

yeah, though not exactly success but just "is done doing whatever it does"

final steeple
#
Func<bool> d = Function1;
d += Function2;

foreach (Func<bool> m in d.GetInvocationList())
{
    if (!m())
        break;
}
#

you can actually do that with delegates like this

#

though a custom implementation can be optimized better to avoid the array allocation

gilded wing
#

would that solve my issue though, i mean my own solution is already functional but the problem was that the stack trace is useless for debug purposes since it all points to the container

final steeple
#

Probably not

#

I'm not sure if you can fix that

gilded wing
#

yeah i guessed as much, was just wondering since i like how simple it's to use and would like to keep it, but that makes it a little sketchy in the long term

final steeple
#

It seems like something that might be worth asking in the C# Discord

#

Plenty of .NET team members hang out there, so if you're lucky one of them might know a way to solve this and chime in

gilded wing
#

hm yeah thanks

viral frost
#

Is there anybody that has experience with Unity's Gaming Services? Particularly with Cloud Code.

I've replicated the Starter pack purchase from the demo into a test project and got it all to work. I want to implement a system where players can buy characters in my game, but only being able to do so once. Therefore I'm trying to make the code reusable by using a parameter, to input the itemID that I want to purchase instead of hard-coding it. But my JS skills are lacking. I'm not sure how to implement it.

I've tried replacing:

 const purchaseResult = await purchasesApi.makeVirtualPurchase(projectId, playerId, { id: "STARTERPACKVIRTUALPURCHASE" });

with the following:

    const purchaseResult = await purchasesApi.makeVirtualPurchase(projectId, playerId, { id: Starterpack });

The Starterpack is a variable I added to the script.

However I'm getting an error:

------------------------------
ReferenceError: Starterpack is not defined

at module.exports (PurchaseStarterpack.js:33:127)```
#

If anybody is able to assist me feel free to @ me. I'll be around doing more digging in the docs

devout hare
#

The Starterpack is a variable I added to the script.
I don't see it anywhere in the script

viral frost
devout hare
#

still not there

viral frost
#

I don't understand

devout hare
#

I don't know what that system is, but it's unlikely that it injects the parameters as global variables. Have you checked the params parameter?

viral frost
#

I haven't TBH. I'm not seeing much documentation or examples to use the parameters of Cloud Code. I'll do some more digging to get a better understanding. I'm way over my head here.

viral frost
stuck onyx
#

help with tasks plz:
i have a scenario :

var returnVal1 = MyTask1Call();
var returnVal2 = MyTask2Call();

// I want to await task1 AND task2 here
var returnVal3 = MyTask3Call();
#

i do know how to await them with Task.WaitAll(myTaskList) but i dont know how to do it when they return values

bold mountain
#

Hey there! is there an attribute or something so that a method of mine gets called when my project gets loaded, but waits that my scene is loaded?

bold mountain
#

oh wait, would that work...?

#

damn

#

trying rn

#

thanks!

#

(cuz it's not in runtime)

stuck onyx
#

you talking on edit time?

bold mountain
#

yeah

stuck onyx
#

ahhh

bold mountain
#

might still work though

stuck onyx
#

yeah, is worth a try

final steeple
#

ExecuteInEditMode isn't really a solution for that

tough tulip
tough tulip
final steeple
#

That would require having the component in every single scene

tough tulip
#

seems like something which would work, but needs an extra gameobject to be in the scene

#

yes

final steeple
#

That'd suck

tough tulip
#

thats why i said indirect (:

final steeple
#

I'd just do InitializeOnLoadMethod + sceneLoaded

tough tulip
#

idk if sceneLoaded works in edit mode thats why i already said "if the above fails"

final steeple
#

I'm not sure sceneLoaded would even be necessary actually

#

There's EditorSceneManager

#

Which probably works

#

Would need to be tested though

bold mountain
tough tulip
#

it should work in edit mode, but limited to only editor if that satisfies your need

final steeple
#

You can do something like

static class EditorSceneCallbacks
{
    [InitializeOnLoadMethod]
    static void Initialize()
    {
        EditorSceneManager.sceneOpened += SceneOpened;
    }

    static void SceneOpened(Scene scene, OpenSceneMode mode)
    {
        EditorSceneManager.sceneOpened -= SceneOpened;
        // Do stuff
    }
}
#

I haven't tested it, but it might work

#

I'm assuming you just want to run some code once when the editor first opens, but after it finishes loading the most recent scene

stuck onyx
#

excuse me @tough tulip

#

is this how you meant?

tough tulip
# stuck onyx

when a task finishes without exception, you can use Task.Result itself

bold mountain
#

but i've done exactly this, and doesn't work

stuck onyx
#

doesnt seem i can access Task.Result in Unitask

#

so... UniTask.Result

stuck onyx
#

i can do.. taskList[1].AsTask().Result; though

#

is it bettter than using the getAwaiter?

tough tulip
stuck onyx
#

thanks man

#

you helped me ๐Ÿ™

final steeple
#

The scene might be loaded when that runs

bold mountain
#
public class Startup {
        [InitializeOnLoadMethod()]
        static void StartupMethod() {
            CharacterCreationMenuItem.CreateCharacterEnum();
            CharacterCreationMenuItem.CreateChoiceEnum();
            if (ScriptableControllersInEditor.instance != null) {
                SceneManager.sceneLoaded += ScriptableControllersInEditor.Hydrate;
            } else {
                ScriptableControllersInEditor.instance = AssetDatabase.LoadAssetAtPath<ScriptableControllersInEditor>("Assets/SCOLTool/Debug/Controllers.asset");
                StartupMethod();
            }

            //Debug.Log("Up and running! Tool ready to be used.");
        }
    }```
#

here's my method

final steeple
#

Is this a scriptableobject?

bold mountain
#

nope

#

ScriptableControllersInEditor is

final steeple
#

that's what I meant yeah

#

which is a built in method for achieving this

#

stuff like the package manager preferences etc use this

bold mountain
#

oh
To have scriptable objects acting like singletons?

final steeple
#

yeah

bold mountain
#

and i thought i invented something new lol

final steeple
#

You'd do

[FilePath("Assets/SCOLTool/Debug/Controllers.asset", FilePathAttribute.Location.ProjectFolder)]
public class ScriptableControllersInEditor : ScriptableSingleton<ScriptableControllersInEditor>
{
    // ...
}
bold mountain
#

thanks so much, i think i'll use this unity thingy from now on lol

final steeple
#

Then you can access it via ScriptableControllersInEditor.instance

#

Note that you need to call the Save method in order to write changes to disk

#

So if you have a custom editor etc you need to do ScriptableControllersInEditor.instance.Save(saveAsText: true)

tulip fox
#

Any ideas why uploading a 1MB Array to a computer buffer (type structured) will result in compute buffer being initialized to 0 instead of uploaded array values

regal olive
#

I am working on an advanced inventory system. Because there are like tons of items there will be spelling mistakes for strings for sure. Is it possible to let the code editor Suggest a string when doing items.add("")? Like it does request "stick" for example

#

Or when I input some sort of ID instead it previews the Associated item name

sly grove
#

Use an enum instead of a string perhaps?

regal olive
#

Could you explain how that would work or give a reference?

lapis arch
#

guys can I bake 2d lighting in unity?

#

I think I'm having performance issues because of them

winter yacht
tender helm
#

Could anybody direct me to a tutorial on creating a gaussian blur against a heightmap or 2d normalised float array?

compact ingot
tender helm
#

I guess the slowness comes from calculating the 3x3 neighbours of every pixel

#

I can at least can started with this info, thanks for the pointer!

wintry wind
#

Hi. I'm making a space game where I have two scenes, one is the location where the player is when he is in su-light speed (fighting for example) the other is the system in hyperspace mode. The player can freely jump between sub-light and hyperspace.

#

The thing is when the player is in sub-light scene I want the system to continue running in the background (so the ships that are traveling in hyperspace continue traveling)

#

An example of this working is Elite Dangerous

#

Is there any simple way to do this?

winter yacht
wintry wind
#

But then my ship will collide with hyperspace objects right?

winter yacht
tender helm
# wintry wind Is there any simple way to do this?

I'm not familiar with Elite, but could you not just keep track of how much time passes and feed that into your Hyperspace scene when you re-load it? That way you'd only need to do a single set of calculations to get the new positions instead of keeping it all ticking away in the background

wintry wind
#

hmm good tip ๐Ÿค”

#

the only problem is that a use case is a ship that's in pursuit that might enter the space the player is in after a while

#

the more I think about this I should just create a simulation that runs in the background (without gameobjects)

sly grove
wintry wind
#

hmm didn't know that existed

#

I'll look into that thanks!

tender helm
ancient talon
#

How can I extract error message from AsyncGPUReadback?

dawn zinc
ancient talon
#

Has anyone had issue with AsyncGPUReadback.RequestIntoNativeArray<T>()?

regal olive
regal olive
dawn zinc
misty glade
#

Architecture problem that's coming up for me often. Thoughts solicited.

I have a game configuration object (persisted to the database, CRUD'd in admin tools) that gets sent to a client. Example: Level and Taps Per Level (how many taps in the client are required to upgrade to the next level). This object is mostly static (not static, but rather unchanging).

I have a client model, with things like "level" and "current taps".

Where should logic go that checks to see if a tap upgrades the level? Should it go in the configuration object, taking a client model as a parameter, in the client, taking a configuration object as a parameter, or in a helper class of some sort that joins the two, perhaps with a static method that takes both objects as parameters?

compact ingot
misty glade
#

LevelUp being a configuration object?

compact ingot
#

being a "manager" type thing in the runtime

misty glade
#

The subscription to the event is a bit harder, since I'm on a client/server architecture, so I have to duplicate/validate/sanitize this on the server

compact ingot
#

possibly on the player object

#

depends on the overall game architecture really

misty glade
#

K.. I can do a manager object in the client, but .. the server would have to duplicate it.

compact ingot
#

only needed on the server i guess... the taps are sent to it right?

misty glade
#

They actually are.. complicated, but taps aren't really 100% "taps" in the client, they can be auto generated by auto-tappers

compact ingot
#

well, whatever you want to use as level-up triggers

#

i'd keep it on the server

misty glade
#

Yeah.. I mean, technically yes but the downside to that is it would require a round trip to level up, and it's not particularly cheat-sensitive

#

If the player sees 5..4..3..2..1 taps to upgrade and then there's a delay, that feels odd

compact ingot
#

well, its the same principle either way

misty glade
#

I could do a static game logic class in the shared library and just call it on both the client and server

compact ingot
#

what you essentially want to avoid is that a tap triggers a roundtrip through all game systems, instead have the tap do what it does locally and fire off events from it, that way only stuff that needs to run, does run and your logic is decoupled

misty glade
#

mm hmm.. good point

#

It's a little bit more complex because I'm not actually sending the updates to the server every tap (obviously), just sending them periodically every 30-60sec (or more, maybe every 5-10 minutes).. but I think that approach is the right one

#

POCO player object that increments taps; static method on the player object that takes a configuration object as a parameter (and can calculate tap-derived data), and the configuration object itself is a POCO

compact ingot
#

maybe you need some client side prediction and reconciliation with eventual consistency

misty glade
#

for some things, yes, but for this i'll just trust the client

#

tap tap tap and they have agency over what level they are - but I can validate the update sent to the server

#

perhaps even count "human taps" and see if it's absurdly large given the time since the last update

compact ingot
#

you can send a lot of ints over the network per second ๐Ÿ˜‰

misty glade
#

i mean, true, but this is also a BigDecimal of my own creation (it's still small, in terms of byte[] size when it's serialized for network traffic), but I'm also hoping to have the server capable of supporting thousands of concurrent players

compact ingot
#

especially if its not a broadcast

misty glade
#

my model is a bit lazy at the moment - the entire player object is serialized and sent to the server on updates

compact ingot
#

okay, thats different then

misty glade
#

it's not huge, but.. you know, it's reasonably big

#

later on i'll denormalize it and just send something like "taps since last update" or whatever

#

but for now..

#
    [MessagePackObject]
    public class ClientSendPlayerModel
    {
        [Key(0)] public PlayerModel PlayerModel { get; set; }
    }

๐Ÿ˜›

#

(that's my network message to the server)

#

and playermodel has....... some stuff in it

compact ingot
#

๐Ÿ˜„

misty glade
#

Ugh, problem. So.. Player Model was going to have an action OnPlayerWarpLevelUp, but I realized that I'm actually periodically sending updates to the client from the server (which the client takes as biblical, so it throws out its local copy). This is going to make unsubbing and resubbing to the events problematic.

Any obvious solutions? I could probably:

  • Pick through the incoming object model, compare it against the local model and update the fields one by one (a really huge nasty piece of work, and probably fragile if I add new items to the object model)
  • Create another event to signal a new POCO has come in, and to unsub from the old POCO and sub to the new POCO
  • Create some (stupid) method like bool CheckForAndDoLevelUp() on the POCO, which sucks because it requires the user of the POCO to both AddTap() and then if (CheckForAndDoLevelUp()) { ... animate the level up, update the UI with the new level, etc ... }
raw lily
#

hey! so i want to make a generic selection ui that can be used at different places in the code. It's built with a list of options and the player picks one of the options and then it returns the value, after the click.
what would be the best wait to do that? i was thinking of maybe using async but i thought there might be a common unity way people go about solving this?

#

maybe just use a callback?

sly grove
#

Yeah use a callback function

#

that'd be the standard way

#

or return a Task if you want to get all Microsoft-y about it.

#

then the caller could choose to use a callback, or to poll for the response, or whatever

dusty bluff
#

Hey yall, asked this before but didnt get any reply hoping someone has some thoughts here. Im using an isometric tile map (z as y).

My q is rather simple, take the mouse position and figure out which tile is being selected. Im using right now Camera.screenToWorld to get the mouse position into a world position and then grid.WorldToCell() to get the cell position.. this works fine but only for the ground level, it doesnt seem to care about the tiles on top. I thought this being an isometric tilemap that it would just work but curious to see if anyone has any ideas?

raw lily
#

@sly grove yeah thought a bit more about it and was also starting to lean towards callback, alright, thanks! ๐Ÿ™‚

civic talon
civic talon
civic talon
#

'FbxTime' does not contain a definition for 'SetSecondDouble' - well that's going to be a challenge... ๐Ÿ˜“

wooden cedar
#

They should have their height, and their tileID. So should be quick to select and sort through

#

Assuming I understand the goal mind you

regal olive
#

Hello, im trying to calculate a position offset

the position offset offsets the camera position when added

#

the goal is to calculate the offset requires to be at a certain position

#

the values I have to try calculate this is

  • My Quaternion rotation
  • My Position
  • Target Position
#

I need to calculate the offset based on my quaternion rotation, what is the best way to go about this?

stuck onyx
#

@regal olive @dawn zinc it's the best editor in the world. Rider

snow solstice
#

Hello! Not sure if this is advanced but is there a way to use a generic function with types defined in code run without using reflection?

#

I saw there is a way to do it with reflection but for me it sounds like overkill

#

I want to do something like this

stuck onyx
#

what you want to do exactly?

#
 public static void RemoveKeyIfNoEntries<T,Z>(Dictionary<T,List<Z>> dictionary, T key)
    {
        if (!dictionary.ContainsKey(key)) return;
        if (dictionary[key].Count == 0)
            dictionary.Remove(key);
    }```
snow solstice
#
MyCoolFunction<typeof(blah)>(arguments)
stuck onyx
#

here you have an example off a generic function

#

i remove the key of a generic dictionary if the list of Z is empty

final steeple
#

You cannot do that specifically without reflection

#

If you don't know the type at compile time, it cannot be passed as a generic argument without reflection

snow solstice
#

I see... thats sad xD

final steeple
#

That's why many APIs offer MyCoolFunction(Type type) and MyCoolFunction<T> is just a wrapper

sage radish
snow solstice
#

Yeah i guess i will have to do an overload with (Type type) no?

final steeple
#

Do you have more context for the example?

stuck onyx
#

why cant he do MyCoolFunction<T>(T argument) ?

snow solstice
#

I dont know T at compile time

stuck onyx
#

oh

#

okok

snow solstice
#

Ok I have a list of types that all of them inherit from the same

final steeple
#

So you control the types in question?

snow solstice
#

But them i have to instantiate the right type when iterating

#

Yes

stuck onyx
#

what i do is cast the types if i have the info

#

not very elegant but it works

final steeple
#

Could you write a small code sample that is more accurate to that?

#

Just trying to get an idea of what you want overall

#

It sounds like you could just use virtuals or an interface

snow solstice
#

The thing with virtual is that i dont have instances of the elementd

#

So i wanted to have virtual static

#

But that doesnt exist

final steeple
#

Fun fact that actually exists as of .NET 6

#

Unity just doesn't have it yet

snow solstice
#

XD

final steeple
#

Well not virtual statics, but you can have them in interfaces now

#

virtuals are coming later

snow solstice
#

Ah

#

Interface that can be called statically?

final steeple
#

If you have a Type and you want to create an instance, you can do Activator.CreateInstance(type) to create a new instance using the default constructor

#

And yeah

#
public interface ISomeInterface
{
    abstract static void SomeMethod();
}

// ...
public static void CallSomeMethod<T>()
    where T : ISomeInterface
{
    T.SomeMethod();
}
snow solstice
#

Oh thats amazing

final steeple
#

But yeah, you can't do this in Unity yet since they don't have support for it

snow solstice
#

I want exactly that xD

final steeple
#

Since it's a .NET 6 thing

#

You can sort of simulate it though I suppose with empty structs

#
public interface ISomeInterface
{
    void SomeMethod();
}

public static void CallSomeMethod<T>()
    where T : struct, ISomeInterface
{
    default(T).SomeMethod();
}
#

then you do

public struct SomeStruct : ISomeInterface
{
    public void SomeMethod()
    {
    }
}
#

But yeah it's not an ideal workaround

snow solstice
#

Hmmm

#

Let me put the example more elaborate

#
public class Info
{
 public Base type:
 public Func<bool> condition;
 public Func<object, BaseData> generateBaseData;
}

public List<Info> InfoList;
public IEnumerator StartAndWaitForAction(object injectData)
{
  foreach (var info in InfoList) {
    if (info.condition()) {
       InstantiateMyThing(info.type, info.generateBaseData(injectData);
       yield return WaitUntilFinished()
    }
  }
}
#

I guess the instantiate my thing

#

Before was done with generics

#

I just need to do an overload with type

#

Aaaand that works?

final steeple
#

What would InstantiateMyThing do?

snow solstice
#

Instantiate a monobehaviour of type type with the injected object

final steeple
#

That shouldn't need anything special since there are already non-generic overloads of methods like Instantiate, AddComponent, etc

snow solstice
#

I see...

#

Ok cool thanks then i was just confused with our actual methods

#

Didnt realize i can just use addcomponent with type

final steeple
#

I should note that you probably should use UnityEngine.Object instead of object

#

Since those are different types

snow solstice
#

Instead of generic

final steeple
#

The latter is actually System.Object

snow solstice
#

Yeah this one is a general object

#

Not a unity object

#

Thats ok no?

final steeple
#

It depends, but it's probably fine if it's intentional here

snow solstice
#

I just wish i could have done it with the virtual static, would have been much more elegant

#

Lets wait for .net 6 then :p

#

Thanks so much!

final steeple
#

Unity estimates that'll happen within the next two years

#

So who knows lol

twilit jetty
#

someone knows why while building some scripts by some stupid shit dont have references? in most stuff its just asmdef files using post processing but while build its just gone idk why

twilit jetty
#

maybe someone knows if its way to strip assets on headless build? aka i have audio files/textures which i dont want to have any size just dummy file

undone coral
#

i don't remember if it's in 2020 LTS

twilit jetty
#

we using Headless Builder asset on 2019 unity and now we using 2021, its any chance its not needed anymore?

undone coral
#

based on the docs for server build, it omits a lot of stuff

#

that would make sense only in game play

#

it shoudl be clear headless builds can definitely render

#

it's up to you to not render

#

but i believe teh Server Build option does what you want

#

is anyone aware of a good v-ray conversion library? especially for maya? it seems so cantankerous to bring pre-existing assets from e..g Turbosquid into Unity because they all use VRay materials

#

or maybe some kind of pro importer for 3dsmax or maya that can correctly interpret or at least easily allow manual override of materials?

supple crest
#

Anyone coding using DOTS + ECS? Are there any good resources for getting started with the current package?

#

I'm worried older tutorials circa 2018/2019 might have lots of outdated information or use outdated base classes and such

undone coral
#

it's not really ready to be used

undone coral
#

you're trying ot do X.MyMethod() where MyMethod is a static "virtual" void MyMethod(this T xValue) { ... } ?

undone coral
nova gazelle
#

I'm trying to adjust the opacity of a tilemap dynamically. This is my tilemap (FadeScript currently doesn't do anything useful):

#

How do I access the right parameters to adjust the opacity? I'm assuming something like tilemap = GetComponent<Tilemap>(); would be a good start, followed by <something>.renderer.material.color = new Color(1, 1, 1, 0);, but I'm having trouble accessing the tilemap

#

Ok, got it. There's another import from using UnityEngine.TileMaps

snow solstice
bitter elm
#

Why wont this pause the game?

#

It wont even enable the menu

#

ok did some debugging apparently the gamestate isnt changing

#

How the hell am I supposed to implement one of the most important mechanics, pausing

brave flower
bitter elm
#

it is

brave flower
#

ok

#

what are you using for game states

bitter elm
#

was trying to follow this

#

but IDK who to trust anymore

brave flower
#

ok

#

ahh this is hard to do without sound

#

can you post your code

#

or more bits of it

bitter elm
#

Sorry I gotta do something

brave flower
#

hmm comments seem to think he is wrong

bitter elm
#

yeah maybe

#

but brackey's tutorial tricked me

#

and im told not to use Time.timescale

#

Who the fuck do I trust?

bitter elm
#

sorry if i came across as rude

#

im just confused

brave flower
#

no its fine

#

i also just had to do somthing

#

you might as well use the event system now that you have it but maby just for having the menu tabs open

bitter elm
#

cause im getting different answers

#

depending on who I asked

brave flower
#

oh

#

you could do both

#

anyway we might as well fix your code

bitter elm
#

yeah i deleted all the shit from that tutorial

brave flower
#

ohk

#

nvm

wooden cedar
#

It will also get more complex when you start wanting to store and retrieve states :)

final steeple
#

But I haven't watched the tutorial video, so maybe the implementation it shows is also bad

#

Using unscaled time like some of the comments suggest isn't a real solution, it's just a bandaid on top of a hack

bitter elm
#

okay i found a solution

#
        {
            return;
        }```
#

putting this in events i dont want to occur while the game is paused

#

along with timescale

final steeple
#

That's an approach that will work better yeah, though why do it with timeScale?

bitter elm
#

so things wont move

final steeple
#

There are ways that are nicer to use that don't require you to add code to every pausable component, but I'm a bit busy with some work atm so I don't want to get too distracted writing up samples lol

bitter elm
#

no its not part of every use of

#
        {
            return;
        }```
#

the timescale is part of the pause script

final steeple
#

Right, I meant that there are ways you can do it that don't need if (PauseMenu.Paused) return;

humble onyx
#

unless you want the PauseMenu to disable all scripts that should be paused , not realy

twin trellis
#

Help how can you instantiate prefabs from a dedicated prefabs folder? (c#)

sly grove
regal olive
#

i have this code:

foreach (var x in blockdata)
{
    if (HasEnoughItems(Items.Item.Stone_Pickaxe, 1) && x.ItemType == Items.Type.Stone_Block)
    {
        foreach (var pick in blockdatacopy)
        {
            if (pick.Item == Items.Item.Stone_Pickaxe)
            {
                foreach (var block in blockdatacopy)
                {
                    if (block.ItemType == Items.Type.Stone_Block)
                        x.BreakTime = block.BreakTime * (float)pick.BreakMultiplicator;
                }
            }
        }
    }
}

Item.Item holds every Item there is in a game, is enum
blockdata holds all data an Item holds, is List<class>
blockdatacopy is just a blockdata to get access to default variables, is List<class>
item.Type holds every Type an item can be, is enum

pick as in foreach grabs the blockdata defaults for stonepick
block as in foreach grabs the blockdata defaults for every item that is some sot of stone
this is all in Update, but the last if statement gets looped somehow (the values are getting smaller each time)
but how could that be? if the copy isnt altered (it doesnt) how could the values get smaller every time (i checked, block.BreakTime gets changed)

cursive horizon
regal olive
#

it should, because i have to get the pickaxes data default values and the blocks data default values

cursive horizon
#

well that's too much looping for me to follow right now, but it sounds like what you think is a copy is not a copy?

reef wren
#

How does one go about making a server authoritative shooting for projectile based bullets

tough tulip
novel raptor
#

is savesystem and storing data advanced?

green rock
#

I probably know the answer to this but I just want to shoot my question here, is there a way for unity ui to render outside the game scene just like how the docking version of dear imgui?

tough tulip
# reef wren How does one go about making a server authoritative shooting for projectile base...

its a very complicated topic. i wanted to avoid typing a long passage first, you can read some good papers on it.
for this to work, the server authoritative movement should be working and setup properly.
for shooting basically, the client needs to know the current server tick, this way when the client sends back the data, the server will know the exact moment the shoot happened (with some +/- in delay which you need to compensate)
when you shoot, send the same tick back to server

i) for raycast based, the server needs to rewind time, check raycast, apply damage if raycast is successful, and restore back the time
ii) for projectile based, the server needs to rewind time, shoot the projectile and then restore back the time

valid flame
#

Is it possible in Unity to get the color of a pixel from a screen? (Not the program, the screen) Basically what a color picker does, but not just internally

Basically, I need to get the color of a pixel anywhere on screen, even if it's not inside the unity window

austere jewel
#

Only via OS APIs

cursive horizon
#

for me the unity color picker does work outside the unity ui

valid flame
# austere jewel Only via OS APIs

I'm currently using an AutoHotKey hack to /kind of/ do this, problem is it's horribly inefficient and requires autohotkey to be installed on the computer. As well as it most likely triggering anticheat

austere jewel
valid flame
frozen imp
cursive horizon
#

oh dang, yeah hmm

valid flame
cursive horizon
#

would it be crazy to like...take a screenshot and sample the pixel?

valid flame
pale pier
#

Hello folks, I need some help figuring out how to rotate a multi part camera model I have so that the lens ends up looking at a defined point.
I need to rotate the two axis shown only, but I can't wrap my head around the math, any pointers would be nice ๐Ÿ‘

valid flame
#

AutoHotKey can manage it without going over 0% CPU usage

pale pier
#

Thanks, will give it a shot

austere jewel
#

I am a little unsure as to whether it would be able to handle your setup so I might take a look at some of the samples and see whether they apply to the scenario

cursive horizon
#

i feel like i saw something about them using it for robot arm animations that seemed like they would be basically that

regal olive
tough tulip
valid flame
#

Wuh oh..

#

I have no idea how to avoid this exception

#

The autohotkey script & unity program run independently, so unless I can somehow perfectly sync them this will always happen eventually

tough tulip
fresh salmon
#

That error also happens when you don't properly dispose of the file handle when you're done using it. Make sure you're using a using statement to do disposable ops:

using (FileStream fs = new()) {
  // Use stream here
}
// stream is disposed here
valid flame
fresh salmon
#

Alright, but make sure you're using that using statement pattern, that closes the stream even if an exception gets thrown into the nested block.

#

It basically compiles into a try-finally block

valid flame
#

i did what you said and wrapped everything in a try statement and commented out of all of the errors, if I can't see them they aren't there :) @fresh salmon

#

this is probably the hackiest thing i've ever made

#

๐Ÿค”

#

nvm I think this was AHK's fault
yep, for some reason it outputs BRG instead of RGB by default

twilit jetty
#

why on unity 2021.2 while building with usage subtarget Server its taking script definitions from subtarget player? its any way possible to force buildpipeline to use x definitions

twilit jetty
#

seems like i cant set server as targetgroup in buildplayer

#

by some dumb reason on linux build in same stuff its using il2cpp soo wtf

winter yacht
kindred tusk
#

Not as far as I know anyway

#

You want to make something like a color picker?

valid flame
#

the current method I have for getting the screen pixels is.. flimsy.

#

as in it causes hundreds of errors per second that I just have to try catch and ignore

#

also I've been awake for like 18 hours now so my code is getting progressively worse

kindred tusk
kindred tusk
#

I think you'd have to use specific code for each OS you need to support

valid flame
kindred tusk
#

It's definitely possible, Photoshop does it

#

In that case there may be something in .NET you can use

valid flame
#
Loop
{
    FileDelete, %A_Temp%/sample.RGB
    ; 0,0
    PixelGetColor, color, 950, 500, RGB
    FileAppend, %color%`n, %A_Temp%/sample.RGB
    ; 0,1
    PixelGetColor, color, 950, 510, RGB
    FileAppend, %color%`n,%A_Temp%/sample.RGB
    ; 1,0
    PixelGetColor, color, 960, 500, RGB
    FileAppend, %color%`n, %A_Temp%/sample.RGB
    ; 1,1
    PixelGetColor, color, 960, 510, RGB
    FileAppend, %color%, %A_Temp%/sample.RGB
    Sleep, 100
}
```(holy fuck discord has ahk syntax?)
this is my *current* method getting screen pixels in autohotkey
#

I literally log their RGB values to a file and then read the file

#

(I take 4 samples to average together)

kindred tusk
#

(i just googled that so no idea if it's useful)

valid flame
kindred tusk
#

I have never actually used windows API directly through unity, I understand that there are some parts missing. But I think it should be at least theoretically possible to use any windows API from Unity?

valid flame
#

my goal is to mimic the lightsync "screen sampler" effect from g hub

valid flame
kindred tusk
#

you can probably find something more recent

#

Literally a decade old hahah

#

But it's also likely that it hasn't changed much

valid flame
#

oh god 2012 was 10 years ago

kindred tusk
#

I know haha

#

When I started using Unity

valid flame
#

I think I was still programming in BASIC back then lol

#

on a nintendo 3ds

wooden cedar
#

10 years ago, I was still using Unity & Unreal full-time :D. Those windows api calls haven't changed iirc. Although pricing was vastly different back then

#

That said, there are smarter systems for DLL support now, so although that old way is perfectly fine and usable, there might actually be some smarter approaches if you really want to dig into it

undone coral
#

don't punish yourself over unity's flakey support for build automation

radiant wave
#

When deserializing transform values, is the order relevant? I'm restoring a game state by serializing the local scale, local rotation and local position of some objects. when I deserialize this, is there a specific order in which to apply the new values? Scale -> Rotation -> Position?
I'm getting some weird deserialization issues and I'm trying to track them down.

lavish plume
#

Saw a mod for Gorilla Tag that allows for custom maps. It exports UnityPackages but with the extension changed to .gtmap

I know it's a UnityPackage because if you try to open it as a UnityPackage in Unity it works

You put the .gtmap in the folder and when you boot the game up it appears in the level selection screen. How can I use UnityPackages for custom levels?

(Extra proof that they're UnityPackages and not AssetBundles is that they save scripts and you can use them)

I assume they're loading them in at runtime or something but I'm not exactly sure

sage radish
lavish plume
#

I think so Idk

#

You make your level and I believe it takes the scene and everything in it

#

And then turns it into a UnityPackage

timber flame
#

(Unity)
Do you separate interfaces/abstract classes from the implementations using different assemblies?
If yes, can you suggest me good naming convention for that?
For example CompanyName.ModuleName.Core for abstraction modules and CompanyName.ModuleName.Implementation for implementations?

sly grove
#

Have never done that no

#

I'd probably do something like modulename.api and modulename.impl

summer summit
#

anyone know how I could achieve flat shading programatically?

#

I have made a mesh in a script but if I recalculateNormals() then it does smooth shading

sage radish
sly grove
#

and do the normals manually

#

RecalculateNormals will interpolate them and give you smooth shading (though not sure what it does when you've properly duplicated the vertices)

summer summit
#

hmm

#

could I do it with a shader?

sly grove
#

Maybe?

#

probably not

#

the normals for such a shader would have to come from the geometry

#

and without duplicated vertices, the normals will not be right

#

maybe for some limited set of simple primitive shapes

#

Why not just do it the typical way, by duplicating the vertices?

undone coral
#

@summer summit i am seeing online that split vertices is the best way to achieve hard edges

#

opensubdiv supports creases but that's really complicated for your use case

undone coral
#

otherwise i don't think you should separate it this way in C#. if you want to do friend use [assembly: InternalsVisibleTo("OtherAssembly")] in your AssemblyInfo.cs

#

this way you can declare internal classes

#

and when you create a new assembly that needs to access them, e.g. one that's part of your broader library, put in that InternalsVisibleTo attribute

final steeple
#

Anything that exports functions via the C ABI can be called

#

@valid flame

using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class PInvoke
{
    [DllImport("user32", ExactSpelling = true)]
    public static extern IntPtr GetDesktopWindow();

    [DllImport("user32", ExactSpelling = true)]
    public static extern IntPtr GetDC(IntPtr hWnd);

    [DllImport("gdi32", ExactSpelling = true)]
    public static extern uint GetPixel(IntPtr hdc, int x, int y);

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static byte GetRValue(uint rgb) => (byte)((ushort)rgb & 0xFF);

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static byte GetGValue(uint rgb) => (byte)((ushort)(rgb >> 8) & 0xFF);

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static byte GetBValue(uint rgb) => (byte)((ushort)(rgb >> 16) & 0xFF);
}
#
var wnd = PInvoke.GetDesktopWindow();
var hdc = PInvoke.GetDC(wnd);
var pix = PInvoke.GetPixel(hdc, x, y);
// Use GetRValue, GetGValue, GetBValue
#

Note that in multi-monitor setups, this will only work for the main monitor

maiden turtle
#

Hi. Has anyone profiled allocations of local functions that capture local variables but are never converted to a delegate? The MS docs on this say that the compiler can take advantage of the fact that they don't escape the local scope to optimize the closure allocation, but it does not say it is required to do so.

final steeple
#

You can look at SharpLab to see what the compiler outputs

maiden turtle
final steeple
#

Look at the IL it generates

#

Be sure to select release mode

maiden turtle
final steeple
#

Those are irrelevant because this is a C# compiler optimization, not a runtime one

#

Unity still compiles the C# with Roslyn to get IL

maiden turtle
#

ok thanks

final steeple
#

The closure becomes a struct here, so it won't allocate garbage

maiden turtle
#

yeah thank you

final steeple
#

Of course, you'll need to tweak it to match the code you have

#

But in the general case it should be fine

bitter crane
#

Hi

regal olive
#

hi

bitter crane
#

Suppose I am taking the photon instantiated value in the gamobject called target so the gameobject target will only get value when something or player instantiated and so but while starting they are showing error such as give value in inspector how to solve this issue

normal cedar
final steeple
#

Ideally you should use UriBuilder instead of concatenating strings manually because that's an error-prone nightmare

normal cedar
#

C:/Users/lange/Documents/ProjectVZ/Assets/StreamingAssets\HeroProducts\Smart.wav

this is the path

final steeple
#

And how are you constructing the path?

normal cedar
#
 StreamingAssetPath = Path.Combine(Application.streamingAssetsPath, SubFolder, SoundAssetName);```
#

Subfolder = HeroProducts

final steeple
#

Hmm

normal cedar
#

my files were .mp3 at first but found those are not really supported and that .wav was better

final steeple
#
var builder = new UriBuilder
{
    Scheme = Uri.UriSchemeFile,
    Host   = string.Empty,
    Path   = StreamingAssetPath
};

You can then use builder.Uri.ToString() to construct a path, btw

#

And yeah, mp3 is a proprietary format so it's not available everywhere

#

I'd recommend avoiding it at all costs

#

wav should work, so that error seems strange if the path is correct

normal cedar
#

exactly.

#

alright ill use the builder thing see if that helps me more.

final steeple
#

Maybe the WAV contains samples in a format that WebGL doesn't support?

#

Though I'm doubtful of that

bitter crane
#

Suppose I am taking the photon instantiated value in the gamobject called target so the gameobject target will only get value when something or player instantiated and so but while starting they are showing error such as give value in inspector how to solve this issue

final steeple
#

Photon as in the multiplayer library?

bitter crane
#

Yes

#

Sure thanks

normal cedar
final steeple
#

Oh, is the file still an MP3?

#

Just renaming the extension doesn't do anything

#

You need to actually convert the file to a WAV properly, they're completely different file formats

#

You could use Audacity or even just ffmpeg to do that

bitter crane
#

Bro have you created any game

final steeple
#

If you use ffmpeg, the command would be: ffmpeg -i source.mp3 destination.wav

#

Just note that this means converting from a lossy format to a lossless format

normal cedar
#

alright well i got audacity installed so ill use that

bitter crane
#

@final steeple bro do you have any games

#

Which you have created

final steeple
#

Not created entirely on my own, but I've worked on a bunch of games sure

bitter crane
#

Wow

#

Can you name any

#

So you might be a professional

final steeple
#

I work at New Blood Interactive, so basically any game published there I've worked on to some extent

bitter crane
#

Oh

final steeple
#

I'm a support programmer, so I've done programming work on Dusk, Ultrakill, etc

bitter crane
#

So do you study or do job

final steeple
#

I work there

bitter crane
#

Oh

#

Right now I am in college so i study

random lava
#

Hi guys, im facing a problem with Photon Networking, can some one help me out? I need to destroy a scene object that is owned by the master client, apparently i couln't find a solution yet.

final steeple
bitter crane
#

@random lava do you know

random lava
#

thank you i havent found the networking group sorry

bitter crane
#

How to make camera follow the player which is instantiated

random lava
#

yes i do

bitter crane
#

So can you help me with this

random lava
#

sure text me private

bitter crane
#

Ok

normal cedar
#

@final steeple converting it normally to wav doesnt seem to have fixed the issue

final steeple
#

Could you DM me the file?

#

I'll try converting it on my end and sending it back to you to make sure

normal cedar
#

what is is interesting to note is this:

#

yh sure

bitter crane
#

@random lava i can't send message because it is not working

random lava
#

send me a friend request

bitter crane
#

Ok

#

Doen

#

Done

craggy spear
#

dunno, why ask a non-code question in a code channel? ๐Ÿค”

crystal wasp
woeful kraken
crystal wasp
#

no

woeful kraken
#

Then you're referring more to level design?

bold mountain
#

I might do something really different though, i'm complicating my own task

final steeple
#

CreateAssetMenu is only for if you want to create it yourself in the asset browser, which you shouldn't do for ScriptableSingleton

bold mountain
#

i'll do something else, way simpler lol
Instead of having my scenarioList inside of my manager in the scene and doing ScriptableSingletonWithMyManagers.Instance.ScenarioManager.ScenarioList.Add(scenario), i'll transform my scenario<List> into a scriptable object containing a list, which i can have as an asset in my project, yadda yadda yadda, way simpler lol

#

thanks so much though! didn't know about this

final steeple
#

np

kindred tusk
final steeple
#

yeah I gave a proper response shortly after, just wanted to give confirmation

normal cedar
#

I seem to be getting this error whenever i try to grab a file from my localhost (this is a build). the build is on a NAS server HTTPS.
I know i am entering the wrong values but i dont know which ones are the right ones. so if any1 can help. that would be appreciated

https://www.toptal.com/developers/hastebin/lozeqavafe.csharp

#

ln 37 - 63

undone coral
#

don't use uri builder

final steeple
#

There's nothing wrong with using UriBuilder, but yes, the wrong scheme is specified there

#

You should use UriSchemeHttp

undone coral
#
var uri = $"http://localhost:8080/StreamingAssets/{SoundAssetName}.ogg";
#

try just doing this

#

you're putting in streaming asset path

#

i think there are a lot of things going on and it's confusing you

#

i'm just guessing where your sound file is

#

it's impossible to know though

normal cedar
#

jup.

undone coral
#

only you know where your sound file is

#

i don't know what its extension is either

normal cedar
#

does it also work with https?

undone coral
#

you know what i mean? you're obscuring a lot of places you are probably making mistakes

normal cedar
#

or http only?

#

this is panic code. i have a deadline to reach ๐Ÿ˜›

undone coral
#

does what also work with https?

normal cedar
#

the same scheme

undone coral
#

i think the right way to do this is

#
var baseUrl = "http://localhost:8080/StreamingAssets";
var soundAssetFilePath = $"{SoundAssetName}.wav"; // or whatever!!
var uri = $"{baseUrl}/{soundAssetFilePath }";
#

does this make sense @normal cedar ?

#

i mean i don't know what the variables are

#

but you can set in your editor "http://localhost:8080/StreamingAssets" when you're testing

#

and then the real path when you deploy it

normal cedar
#

yeah it does make sense

undone coral
#

that notwithstanding, you're going to screw up things like CORS...

#

have you ever deployed a WebGL game before?

normal cedar
#

no first time

undone coral
#

or are you uploading this to itch.io / some other site?

normal cedar
#

no internet network on an isp

#

its for a training but nonetheless.

undone coral
#

have you been able to successfully play a webgl you built yourself in a browser?

normal cedar
#

yeah.

undone coral
#

okay that's good

#

i mean outside of localhost

normal cedar
#

yeah

#

webgl is just difficult tbh because i find it a bit lacking on documentation

tulip fox
#
            #include "UnityCG.cginc"
            #pragma multi_compile_instancing
            struct appdata
            {
                UNITY_VERTEX_INPUT_INSTANCE_ID
                uint vertID : SV_VertexID;                
            };
            struct v2g
            {
                float4 vertex : SV_POSITION;
            };
            
            v2g vert (appdata v)
            {
                UNITY_SETUP_INSTANCE_ID(v);
                UNITY_GET_INSTANCE_ID(v);
                uint instID = unity_InstanceID;
                //uint instID = 1;
                uint vertID = v.vertID;

            }

any idea why unity_InstanceID would be undeclared identifier?

fresh salmon
supple crest
#

Are ECS principals workable in Unity without the ECS package? Would they have any benefit? What would it look like?

compact ingot
# supple crest Are ECS principals workable in Unity without the ECS package? Would they have an...

in principle you can use DOD and by extension an ECS wherever/whenever you like. Unity ECS is just one implementation of the idea. The benefits depend on what you are using it for. The architecture alone can be of great benefit even when used with GameObjects to make things more reusable/easier-to-change/simpler. You should be able to get the most out of your custom ECS when using it for non-rendered, non-gameobject based code where you can also reap the performance benefits.

supple crest
compact ingot
supple crest
# compact ingot DOD has potential to improve performance by multiple orders of magnitude (compar...

Interesting -- I will have to do more tests. I'm pretty new to DOD so still trying to figure out how I would write systems that would show any performance uplift for traditional game loop stuff (modifying transform positions, rotations, state booleans, for many players). Seems you want to be passing small structs with few blittable parameters like float2s and iterating over those using jobs? But like you said, even if done on the main thread, if the data was aligned optimally for the CPU there should be performance uplift.

valid flame
fresh salmon
#

The interop is built-in yeah, but it makes calls to external DLLs that must be on your system

#

If you build for anything else than Windows it won't work

#

But yeah, it's a powerful way to interact with the system

final steeple
#

Pretty much, yeah

#

I have my own system for calling internal engine functions this way too

#

So I can get notifications for when a GameObject is created or when a component is added

summer summit
#

seems like it must be doable with a shader but I don't know much about them

sly grove
#

Sounds like you're trying to prematurely optimize things

#

Shaders can have performance issues too

summer summit
#

hmm maybe but I wanted to put a shader on here anyway

sly grove
summer summit
#

sure

valid flame
fresh salmon
#

On Windows by default

valid flame
#

damn, thought it might've been the cause of the bug I have

#

When I try to share the project with other people, their screen seems to not get sampled at all even though the screen sampling service is running

final steeple
#

Do those people have multiple monitors?

#

It only reads from the main one

fresh salmon
#

Know that you can debug this, the DllImport attribute can have a property named SetLastError set to true, which pushes an eventual external error onto somewhere, where you can retrieve it with yet another external call to GetLastError()

final steeple
#

That's not what SetLastError is for

#

SetLastError caches the Win32 GetLastError value, it only applies to functions that actually use that system

#

The functions in that snippet don't use it

valid flame
#

I already asked them if ANY of their monitors were black while it was running and they all said no

fresh salmon
#

Then make sure they're picking colors on the main monitor

final steeple
#

You can retrieve it via Marshal.GetLastWin32Error()

#

But anyway, if the DLLs were somehow missing, it would throw DllNotFoundException

final steeple
#

But if user32.dll was missing, Windows wouldn't even run

valid flame
#

i know one of them is on windows 11

final steeple
#

Same for gdi32.dll

#

Since both of those are core system DLLs

valid flame
#

but anyway with that code you gave me i should be able to remove the dependency on the seperate screen sampling service

#

which will make it 1000% more reliable

final steeple
#

It should be more performant too because you're not going through disk IO

valid flame
#

and much much much faster

#

I could only reliably sample the screen every fifth of a second before

final steeple
#

Yeah you can reasonably do it every frame now

valid flame
#

also I can get a lot more samples now

final steeple
#

Just cache the IntPtr you get from GetDC (DC means Device Context), I'm not sure of the performance characteristics of that function

valid flame
#

I'm still working on that other store project rn, but I'll get back on that screen sampling project later now

#

I'm removing the dependency on visual scripting since its just bad

drifting tusk
#

I simply just need to clamp the player camera X rotation to not flip around when the mouse moves, and this is the best method I have found - and it doesn't really work. Camera still flips when i reach the top and mouse moves the opposite way to go down too fast. (I am not good with quaternion math- and exposing camRotation.x did not help in the least, as making modifications just caused a ton of odd camera movements)

    Vector3 camRotation = cam.transform.rotation.eulerAngles;
    camRotation.x -= look.y * lookSensitivity * Time.fixedDeltaTime;
    camRotation.x = ClampCameraX(camRotation.x);
    cam.transform.rotation = Quaternion.Euler(camRotation);//Move camera up/down

    private float ClampCameraX(float angle) {
        if (angle >= 270) {
            return angle - 360;
        }

        if (angle > 90) {
            return 90;
        } else if (angle < -90) {
            return -90;
        } else {
            return angle;
        }
    }
lavish plume
#

Replace all of that with

drifting tusk
#

Mathf.Clamp cannot be used with quaternion -> Euler angles, the math breaks

lavish plume
#

Mathf.Clamp(angle, -90, 90)

First argument is the float to clamp
second is the minimum value it can go to
third is the highest value it can go to

#

For me it works

#

Hold on

austere jewel
#

You should track your own values that you modify, clamp, and re-apply as a rotation

#

you should not try to get rotation from an object and clamp that

#

unless you have a very specific range of motion and rotation modifications that can happen it's just not gonna work

drifting tusk
#

That is definitely one method i was considering, but sounds kind of excessive considering the variables exist already in another โ€˜formโ€™

I had an old project i had it working with, clamping vertical rotation perfectly between 90 and -90 on the euler X axis - but i lost that project :/

austere jewel
#

It's not excessive, the rotation does not exist in another appropriate form

#

it only exists as an orientation without knowledge of any rotation about axes

drifting tusk
#

Thatโ€™s what Euler does, but clamped in i believe 0-360

austere jewel
#

Unity does not store euler angles (outside of the inspector)

#

the euler angles are entirely derived from the quaternion, which doesn't have any knowledge of x y z rotations about axes

drifting tusk
#

Euler is the converter between the two, giving me back out the active angle and not one that by some poor mistake could be off

#

and properly setting back with Quaternionion.Euler(vector3)

#

itโ€™s messing with camera - so the least amount of jitty possible is best (which will happen if somehow camera becomes desynced from store variables), so best to modify the active angles

#

it nearly worked with MathF.Clamp(), but when it reached around the middle, it would instantly flip down to 90

drifting tusk
#

Thank the heavens a friend had a copy of the source. Found the original function I had used, and now it works like a charm (Similar to what I had shown before, but better scripted to support quaternion math in euler).

BTW, on the side, am I experiencing a bug/glitch or is this just how Unity works? If I set a RaycastHit object's parent, if I do any GetComponent calls on the hit, it performs the search based on either the parent most GameObject or the script containing the GameObject that called the hit.Transform.SetParent (Hard to tell, since both fit my current situation). This is not a problem for me as all I have to do is perform SetParent last, but I was curious it this was an issue or if that is just how Unity works.

In this example, if Collider.enabled = false was called after SetParent, the GameObject running this script would have its collider disabled instead

    if (hit.transform.GetComponent<SceneItem>() != null) {//Pickup if interactable is SceneObject
        hit.transform.GetComponent<Collider>().enabled = false;
        hit.transform.position = Vector3.zero;
        hit.transform.SetParent(hand.transform, false);
    }
sudden idol
maiden turtle
sudden idol
#

@maiden turtle thanks!

sudden idol
#

I have another problem with generics.
I have these 4 files : https://paste.ofcode.org/simBb9bGCNUYijS5ML8768
If I add an IntGameEventListener script to my object, the selector window for Event is empty. I can however drag and drop an IntGameEvent instance to the Event field (and it actually won't allow me to drag something else there). Is there a way to make my events show in the selector window?
Or a different way of writing this code for that to happen?

compact ingot
sudden idol
#

Other than copy pasting the code for all of the types of events and event listeners, is there a way to make this work? I know that if I have a field explicitly for IntGameEvent then those events will show up in the window. Is there to rewrite as little of the code as possible between the different classes but somehow specify the type of Event explicitly?

compact ingot
sudden idol
final steeple
#

You can implement the non-generic GameEvent and then implement GameEvent<T> on top of it, but really this is just something you have to deal with in C#

#

Even the BCL has to deal with this, examples being stuff like Task and Task<T>

#

Or the existence of Action vs Func

maiden turtle
#

You can use my code generator too. It's plugin based, so it's going to be less work than writing one from scratch

final steeple
#

There's also C# source generators, though Unity doesn't support incremental ones yet

#

Incremental ones are much more efficient, so hopefully that changes soon

maiden turtle
#

(and its a bit messy from the build side of things)