#archived-code-advanced

1 messages Β· Page 17 of 1

tame tartan
#

the drawings are parented to the canvas, but i dont really know what what does "setting transform z" to be pointing out of the page mean? like making transform.forward match with the page forward?

tame tartan
#

one of the problems is that when i set the drawings to local space, they appear basically somewhere else entirely

undone coral
#

i don't know whether your page is facing 0,0,1 or 0,1,0 or..

undone coral
#

and reason about this in your head first

regal olive
#

Ok I'll ask again then

tame tartan
#

the page only has one rotation, and its -39 degrees on the x axis

undone coral
regal olive
#

Does anyone have any documentation on what batchmode does exactly, and specifically how it should affect rendering except for not calling Camera.Render() ?

undone coral
regal olive
#

I'll do that

tame tartan
undone coral
#

okay

#

when you say rotating the canvas

#

i see the paper graphic

tame tartan
#

okay i see where the misunderstanding could come in

undone coral
#

i mean, surely the line renderer is parented to the paper?

tame tartan
#

so when i turn my camera, the canvas turns with me

undone coral
#

i asked you if it's supposed to be naturalistic

tame tartan
#

the line renderer is parented to the paper

undone coral
#

is it?

tame tartan
#

the paper is parented to an empty which tracks the camera rotation

undone coral
#

is the goal to have everything behave naturalistically?

tame tartan
#

yes, the first two screenshots are more or less how i want it to act, with the exception of the ends of the lines connecting to the center of the canvas for some reason

undone coral
#

i suggested

tame tartan
#

just did

#

i found a github but not sure if its exactly what im looking for

undone coral
#

it looks like there are a lot of bugs in your code

tame tartan
#

most likely lol

undone coral
#

i think the hard part is translating the behavior into code

tame tartan
#

there are a few bugs ive fixed between my posting of the code and now, evidenced by how the canvas now rotates the first time at least

#

but yeah

#

a lot of it is really messed up

undone coral
#

so

#

i mean this is for a game jam

#

you can use the github repos that try to solve this

#

there are many ways to draw

tame tartan
#

i was kind of hoping that someone would provide me a solution to rotate an array of points around another point in space so i could just scrap what i had and use their solution

undone coral
#

which if you have all these bugs

#

why try to reinvent the idea of local versus world space

#

you're not going to do that correctly, as you can see

tame tartan
#

i suppose so

undone coral
#

so...

#

you have to use local space

#

you are actually really close

#

your raycasts are wrong

#

you should just try to fiddle with things in play mode

tame tartan
#

hmm

#

can i run an idea by you

undone coral
#

like change the alignment to transform z

#

i mean i said all this stuff already

undone coral
tame tartan
#

so right now i get the position of the line by raycasting onto the page, then basically lifting the line off the page by moving it in the opposite direction of the raycast direction (so the line doesnt clip into the paper)

#

but this hit.point is a global position

#

when i set the line renderer to local space, it makes the lines appear like, 50 miles away from the canvas

#

do you think that the fact that hit.point is a global position, combined with the local space setting is causing this?

#

and if so how would i take the hit.point and convert it to local space

undone coral
tame tartan
#

let me show you instead of explaining

undone coral
#

because it's not transformed to local space

#

i've been saying what to do

#

anyway i think you'll figure it out πŸ™‚

tame tartan
#

would i use transform.inversetransformpoint to turn the hit.point into local space?

tame tartan
#

ok thank you dude

#

seriously thank you

misty glade
#

What's your goal? To ensure you don't forget a particle component on a GO with a script that depends on it? If so, I tend to just add my Assert.IsNotNull() directly in the script itself (since they're compiled out for production builds) - I find out right away if I forget a component or whatever

#

@regal olive

#
public class MissionIcon : BetterMonoBehaviour
{
        [SerializeField] private TextMeshProUGUI StatusText;
        private void LocalAssert()
        {
            Assert.IsNotNull(StatusText);
        }
        private void Awake()
        {
            LocalAssert();
        }
}

that's my standard pattern

jolly token
#

If you wanna spend whole day making tests for cosmetic stuff sure πŸ€”

terse bobcat
#

does anyone know how to add camera shake if a player is running?

snow rapids
#

Kinda feels like one of those tests you write to verify requirements instead of behavior. Having a particle system with spheres is probably not sufficient to prove it's what you need.

split folio
undone coral
#

as my super discount documentation

#

we don't have infinite time on this earth to write all the instructions

#

then again anything i share as source people can always modify if GetComponent based workflows are inadequate

#

so it's worth just doing everything as easily nice friendly base case as possible and owrry about power users later

misty glade
#

1500+ errors

#

(since i have warnings as errors in my codebase)

#

solution:

#

πŸ‘€

haughty sun
#

is it possible to have a custom package has a dependency on a another custom package? because i'm getting errors.

jolly token
hardy sentinel
crystal ridge
#

How can I write my own built in function that has a specific execution time? Specifically, I want to make my own globally accessible (identified by monobehavior) method called LateStart(); that fires off after Start()

Is that something pretty simple to do?

jolly token
#

You can make specific script execute faster/later than others

#

You could expose event from that script for other scripts to subscribe

haughty sun
#

@jolly token is open-upm widely used?

austere jewel
#

Yes

dapper nest
balmy cargo
#

does anyone know why my database initialization doesnt work ?

#

it's a brand new project with an empty scene that has an object containing the script above

flint sage
#

Probably beacuse it's async and it's not done connecting

random dust
#

You're checking for fb_db immediatley after calling Check_Dependencies

#

Which is synchronous but FireBaseApp.CheckAndFixDependenciesAsync is not

#

If this method is only done once, consider making a component that initializes it for you when the application starts

#

Then add a method to it that accepts an Action that can be called when you actually initialized the database

#

Because you never know when it is

#

So you store those Actions in a list in the monobehaviour and have an Update method inside of it invoke them all as soon as the database exists

#

Just remember all those calls will be asynchronous as well, because they are in databases

#

So the tas that represents this operation will have to be stored aswell

#

Welcome to Asynchronous programming in Unity

#

Unity avoided asynchronous programming and now it will bite you in the ass

#

Creating a general system that can store all of this for you is probably the best answer. You will store all delegates in it and whatever should happen with the result. It's basically the old callback hell that you used to have before async-await programming, but now you manage it yourself

#

But you can also try it all with ContinueWith(). Just remember that the moment you call _task_.Result, the result might also throw an exception

mint sleet
#

Hello! I have a backend system to make it work in Unity. But do not want to cal APIs directly. I'm thinking to code a library sitting in the between Unity and Backend.

#

In order not to suffer from versioning in the future, I need to make a very wise abstraction, for sure.

#

Do you have any suggestion before I start? Thank you

#

So from user login to all CRUD operations will be handled by this Library with Unity objects.

#

in the meantime, however, the API v2.0 will come and I do not want to break my previous applications using the version Library 1.0

undone coral
wraith snow
#

@mint sleet it sounds like you need to separate any calls into your dB into a separate datalayer class or project. Then you can code a data adapter between your client calls and the data layer, which would abstract the calls and help wit versioning

#

@balmy cargo if your async method needs to finish you can call GetAwaiter().GetResult()

#

I use that often in business applications where we have async and sync colliding

undone coral
wraith snow
#

It's literally the MSDN recommendation

undone coral
#

it is bad advice

wraith snow
#

Why

undone coral
#

it isn't the right way to interact with unity or the firebase unity api

#

the original user is gone anyway, but i think @balmy cargo will quickly start to comprehend what is going on

#

without anything too complicated

#

@balmy cargo doesn't know what the Async means and provided he googles that, he'll be fine

wraith snow
#

You can't await in synchronous context. He needs to either get awaiter or use async code. You haven't explained why you shot down my answer at all

limpid prairie
#

Hey guys, I have a question about detecting "bunched up" gameobjects.

Let's say I have a map of a few mobs in it, and I want to cast a AOE spell onto the area with the most bunched off mobs

#

How do I detect via where to place the spell?

wraith snow
#

Pretty sure this is traveling salesman

#

Good luck

undone coral
wraith snow
#

I'm very experienced in untiy. You still habet provided an answer

limpid prairie
#

I have map 1), and need to know where to cast spell such that I cast on map 2)

jolly token
limpid prairie
wraith snow
#

You could do a KD tree and spit into certain size zones then count in zones

balmy cargo
#

thanks everyone

wraith snow
#

Or do n^2 comparisons and measure all distances

limpid prairie
#

😳 A KD Tree, true

#

I haven't touched that stuff since Uni, but I feel like that's its purpose

wraith snow
#

Having an ai always have the right answer could be very difficult

#

Maybe try randomly selecting 10 units and then see which has the most neighbor's?

#

You could find a local maximum but not be the most efficient

limpid prairie
#

For most simplest and basic way, I could just divide the map into 4x4 cubes, and run overlap sphere on it, and see which one resulted in most mobs

#

obviously accuracy wise this isnt better than a KD tree but this is very cheap comp wise

wraith snow
#

Cheap and fast is good you can iterate on it later

limpid prairie
#

yeah true, I'll start with this for now

#

Thanks!! @wraith snow

undone coral
wraith snow
#

Aye it's traveling salesman just worded differently

undone coral
#

consider that most of the time, the center of the optimal circle will not lie on a unit itself

limpid prairie
#

Well, once you have a rough idea of the bunched up quadrant, then take all the mobs in it

#

then average out their pos

undone coral
#

additionally, k-d trees don't really give you the right shape

limpid prairie
#

it just involves many layers of steps

undone coral
#

there is a datastructure for circular ranges

#

but i think that's pretty premature

#

consider what the problem would look like in 1D

wraith snow
#

Yeah honestly from game play perspective, randomly selecting a unit and then doing a spherecast for other units or something might be the best bet

#

But then you would always center on a unit

#

And you'd have to accept "good enough"

limpid prairie
#

I think what you can do with KD tree is, find out the most populant quadrant,

then discard the KD tree, take the all the mobs in that quadrant, get the center mob, then now, scan all mobs near this mob within X distance, and get average of that to get ur circle's center

wraith snow
#

The goal of the attack is to hit a unit? Wouldn't you rather always be centered on one to increase those odds?

limpid prairie
#

so even if the most "bunched up" mobs fall under 2 squares, and not just 1, then you can still cover both

undone coral
#

don't get anchored on this kd tree thing

limpid prairie
wraith snow
#

I could see it working either way

#

Up to you

limpid prairie
#

I definitely got some ideas here to expand on it, but Ill do the basic one first

undone coral
#

hmm

#

really seriously try to do this in 1D

#

you are getting derailed by someone

wraith snow
#

1d? That's just a line. Do you mean 2d?

undone coral
#

i think i figured it out by following my own advice

jolly token
#

You could adapt dynamic programming

undone coral
#

i wish you would try...

wraith snow
#

You could also try building some kind of heat map and jumping to the place with the highest "temperature"

undone coral
undone coral
#

you don't really care about the region with the most points you don't care about a rectangular area that has a lot of points

wraith snow
#

At least I'm giving ideas not riddles

undone coral
#

a k-d tree doesn't help you

#

i think the other key insight here is that, why assume there is only one point that is the best location to cast

#

there will be a region of points

#

this is clear in 1D

#

in 1d you can draw lines of length Radius of Spell on each unit. the interval (the region between two points) with the most overlapping lines - any casting position in that interval will have the maximum number of units targeted

#

@limpid prairie in 2d you would draw circles on every unit, of radius spell effect. any point in the region in your image with the most overlapped circles would have the most units hit

#

@jolly token in 1d, the dynamic programming is easier to see - i think the reason it works is because as you query more points

#

the overlapping regions with the most number of points can only be the same length or narrower

#

i'm not really sure how to translate that into 2d though

#

it might not be true in 2d if you are querying point by point, there is something else you have to do

#

yeah i think you can do it point by point in 2d. you will want to preprocess the distance between every point - in this sense the data structure that supports circular range queries will help you. the range you are interested in is 2 * spell casting radius, because that will identify the (narrowing) region of best cast positions

#

i'm just not sure how you deal with the weird shapes you get when you overlap circles :/

#

anyway pretty good problem

#

okay i think it's

#

This kind of problem is NP-complete problem.

undone coral
#

yeah

#

i think that makes sense

#

yeah

#

@limpid prairie you should use the greedy algorithm from that paper with number of disks = 1

#

if you have a lot of units you will have to use RKCP2 as specified

#

and it will be an approximation

#

but it wasn't tested with 1 disk

#

thanks for finding this @jolly token πŸ™‚

#

greedy is fine - it's O(n^2)

jolly token
#

Yeah it is pretty interesting question

undone coral
#

i was having trouble expressing it

#

now we know

#

"robust disk covering"

limpid prairie
#

Oh damn wtf

#

But isn't that computation-heavy though?

#

Ofc that gives the best results

#

collision checking in Unity isn't the lightest, but I guess this spell isn't going to be cast often so it's totally feasible

languid sinew
#

Hello, I need help saving a list variable as a json file

#

and then decoding it back into that variable

shadow seal
#

JsonUtility can't serialise a List<T> so you'll need to put the List into some wrapper class like

public class SaveBlah
{
  public List<T> MyListOfThingsToSave;
}
placid jacinth
#

As other channels are busy I'll pop this in here, is there a way to convert or pass in a System.Type variable in place of writing the actual class name?

misty glade
#

I did something that works but.. might be godawful, lemme dig up the code

#
    /// <summary>
    /// If you can read and understand this method without semantic satiation on "type", 
    /// you win a prize: https://stackoverflow.com/questions/43080505/c-sharp-7-0-switch-on-system-type
    /// </summary>
    private Container GetContainerFromType(Type type) => type switch
    {
        Type _ when type == typeof(PlayerModel) => _cosmosPlayerContainer,
        Type _ when type == typeof(SpaceGameSettings) => _cosmosSpaceGameSettingsContainer,
        Type _ when type == typeof(UserMetricsModel) => _cosmosUserMetricsContainer,
        _ => throw new NotImplementedException(),
    };
#

comment included because it still makes me laugh

#

i read that article one day and after could not make my brain comprehend the word "type" any longer

placid jacinth
#

lol

misty glade
#

(obviously you don't have to switch/return something, but since you're in advanced I'm sure you can pick out the useful bits without help)

placid jacinth
#

Thanks, I'll try and digest that :)

undone coral
jolly token
jolly token
sly grove
#

this exists

#

you need a name/path though

jolly token
#

Yeah for Unity APIs they have it, Idk what AssetUtilities is

placid jacinth
#

AssetUtilities is mine

#

i can change the function on the other end

#

it basically returns a list of all assets of a type

jolly token
#

Okay how does that one look like, you can have overload that accepts type parameter

placid jacinth
#

1 sec :)

sly grove
#

instead of a type paramater

#
List<UnityEngine.Object> LoadAssets(Type t) {
  ...
}```
#

Of course you will lose compile-time type checking here, which is expected since the type is now determined at runtime.

jolly token
#

Yeah then use AssetDatabase.LoadAssetAtPath(string assetPath, Type type); version

#

Converting to your preferred type later

placid jacinth
#

No errors, so I will test this rn, but is this how you guys meant? (thanks for the help by the way :D)

jolly token
#

Yes

placid jacinth
#

oki checkin now :)

#

@jolly token @sly grove Big thanks to you both, it works all good, I was driving myself insane over that as usual lol

maiden turtle
#

you can still make it generic if you cast to T after loading

odd shale
#

Hi im trying to read data from my mysql database, and it gives me an TlsException: Handshake failed - error code: UNITYTLS_INTERNAL_ERROR, verify result: 4294936704
code:

fresh salmon
#

You might need to explicitly tell MySql to not use a certificate when connecting to the server. This is usually done in the connection string. You'll have to look at the docs to know how, though.

#

Fair word of warning though, I googled your error message, and told it to search for this error explicitly (no fuzzy searching), and I got 4 results, in which 3 of them were copies of the first one

odd shale
fresh salmon
#

Yeah

#

Looks like a Unity issue though, see if you can reproduce the error but outside of Unity, in a console application for example

odd shale
fresh salmon
#

Yep, so you determine whether the issue comes from Unity, or MySql

#

If you don't get the error with the exact same setup, then Unity is at fault

odd shale
#

OK, also idk if I'm going overkill cuz I'll I need is couple of buttons and gui with mysql, do u recommend something less overkill?

#

Ok*

fresh salmon
#

Like, you're making a SQL query runner or something?

odd shale
#

It's something for school with a machine we built for producing energy, and every student has a score, so the data goes to mysql and the app just takes the data and displays a leaderboard

fresh salmon
#

So no game at all, just GUI?

odd shale
#

Ye that's why I'm saying I think I'm going overkill but idk any other engine

fresh salmon
#

Yeah Unity isn't the thing you're looking for here, if you wish to keep C# you can make GUI apps in C#

odd shale
#

And now that I think about that, a website would be better cuz ios problems and stuff

#

Is it easier in Java script to work with mysql?

fresh salmon
#

Depends on the framework that you use, but I'm sure most of them (like Node.js, React, etc.) have MySQL connectors

odd shale
#

Alright, I appreciate the help πŸ™

icy aspen
#

hi, i have a question. I only want my touch control buttons to show when the game is running on mobile. The problem is that my game is built on webgl.

coarse charm
#

        public class myClassA:MonoBehaviour
        {
            public myClassB;

            async private void Start()
            {
                await myClassB.DoSomething();
                //continue with other stuffs
            }
        }

        public class myClassB : MonoBehaviour
        {
            async public Task DoSomething()
            {
                await Task.Run( () => {
                    //stuff
                    
            });
        }
``` Im having a NullReferenceException and a TaskCanceledException
#

I did assigned myClassB through the inspector so myClassA has a reference, any ideas on how to solve this?

fresh salmon
#

First things first, post the full errors, stack traces included

coarse charm
# fresh salmon First things first, post the full errors, stack traces included

okey ```
NullReferenceException: Object reference not set to an instance of an object
Namespace.ClassName+<FunctionName>d__49.MoveNext () (at ScriptLocation:LineOfCode)
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.TaskAwaiter.GetResult () (at <695d1cc93cca45069c528c15c9fdd749>:0)
NameSpace.ScriptThatCalledTheFunction+<Start>d__11.MoveNext () (at ScriptLocation:LineOfCode)
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__6_0 (System.Object state) (at <695d1cc93cca45069c528c15c9fdd749>:0)
UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () (at <3be1a7ff939c43f181c0a10b5a0189ac>:0)

coarse charm
# fresh salmon First things first, post the full errors, stack traces included

the other error TaskCanceledException: A task was canceled. System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0) System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0) System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0) System.Runtime.CompilerServices.TaskAwaiter.GetResult () (at <695d1cc93cca45069c528c15c9fdd749>:0) Namespace.ClassName+<FunctionName>d__2.MoveNext () (at ScriptLocation:LineOfCode) --- End of stack trace from previous location where exception was thrown --- System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () (at <695d1cc93cca45069c528c15c9fdd749>:0) System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0) System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0) System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0) System.Runtime.CompilerServices.TaskAwaiter.GetResult () (at <695d1cc93cca45069c528c15c9fdd749>:0) NameSpace.ScriptThatCalledTheFunction+<Awake>d__91.MoveNext () (at ScriptLocation:LineOfCode) --- End of stack trace from previous location where exception was thrown --- System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () (at <695d1cc93cca45069c528c15c9fdd749>:0) System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__6_0 (System.Object state) (at <695d1cc93cca45069c528c15c9fdd749>:0) UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () (at <3be1a7ff939c43f181c0a10b5a0189ac>:0) UnityEngine.UnitySynchronizationContext:ExecuteTasks()

undone coral
#

it's telling you what the error is

fresh salmon
#

Namespace.ClassName+<FunctionName>d__49.MoveNext () (at ScriptLocation:LineOfCode)
That's not valid, please don't redact information from messages

undone coral
#

you obscured too much of your code

#

//continue with other stuffs
ah yes, stuffs

fresh salmon
#

Stack traces contain essential info, especially where in the code the exception was thrown

#

We need that info in order to debug

#

What I can say though is that both errors are related, the NRE forces the task to cancel at some point

coarse charm
#

yeah, its kind of hard when you have a NDA, anyways Im trying to await the response of a fetched data from a database, and according to whats in the data continue with the logic, the script that handles the fetch is separated from "myClassA" thats why I make a reference through the inspector.

undone coral
#
async public Task DoSomething()
            {
                await Task.Run( () => {
                    //stuff
                    
            });

what is this actually doing?

undone coral
#

you should be using UniTask

#

are you trying to access a database with a blocking IO API?

#

and you are trying to "taskify" it?

fresh salmon
#

Most database providers provide async calls

#

Check the documentation of yours

#

Without the essential info, can't help further

jagged harness
#

Hello. Maybe someone can help me read value of some UUID? I am using Bluetooth LE for iOS, tvOS and Android. My script

#

public void ReadBattery()
{
BluetoothLEHardwareInterface.ReadCharacteristic(_deviceAddress, ServiceUUID, ButtonUUID, (data, bytes) =>
{
Debug.Log("Read Succeeded " + bytes);
});
}

jagged harness
#

in respond i am getting "System.Byte[]".

sly grove
#

C# Guid is the same as UUID

#

assuming your byte array is actually a 16 byte guid, you can use this constructor

jagged harness
#

i tried this one - var str = System.Text.Encoding.Default.GetString(result);

#

But looks like i am not getting value, but just uuid...

sly grove
jagged harness
#

Its too hard for me, sorry πŸ˜„

sly grove
#

what's hard?

jagged harness
#

And this is looks like work with UUID not of this value?

coarse charm
sly grove
brisk pasture
#

guessing the implementation of uuid is not the same as the guid

sly grove
#

UUID and GUID are the same

undone coral
#

in a sec

#

but you have to tell me what htis is actually for

coarse charm
undone coral
#

i mean what is the application / game

#

i'm sure you can say enough in broad strokes

#

this is just part of being an engineer

coarse charm
undone coral
#

for example, "i am building a virtual test drive experience in Unity for an auto brand"

#

does that make sense?

#

or "i am making a first person shooter strongly influenced by CS:GO" <-- valorant

coarse charm
#

why would you want to know that?

undone coral
coarse charm
#

then it isnt free at all

undone coral
#

i'm saying part of what you can learn today

#

is how to describe what you are doing

#

and understand that it doesn't violate any NDAs

#

i.e. "Not Doing Anythings"

#

it's too bad because

#

the solution to your problem is 3 lines

coarse charm
undone coral
#

alright well so it goes

#

consider that there are certain things that i categorically do not want to help, as i am entitled to!

#

everyone has a line

#

i want to help people make games

#

you're talking about accessing databases

#

from inside unity

#

and i'm not the only person who told you that the amount of obscurity you are operating in is so annoying

#

two other people who have tried to help you ran into basic issues understanding what it is you are trying to do

coarse charm
#
        {
            public myClassB;

            async private void Start()
            {
                await myClassB.DoSomething();
                //continue with other stuffs
            }
        }

        public class myClassB : MonoBehaviour
        {
            async public UniTask DoSomething()
            {
                await UniTask.Run( () => {
                    //stuff
                    
            });
        }```  Im getting a new error, not all path return cant recall what
undone coral
#

πŸ™„ who knows really

#

@jolly token c'mon "NDA" = "Not Doing Anything" is pretty good

jolly token
undone coral
#

lol

brisk pasture
#

thing is that code makes little sense, how are you expecting the new task to run

undone coral
#

i think the user is trying to access a database with a blocking API

#

but that's just my guess

brisk pasture
#

Tasks and async and await, does not make things concurrent its just tools for working with concurrent stuff and repersenting futures

undone coral
#

i'm not trying to be a blowhard, it just would really make my life easier to know some basic facts about what is going on

brisk pasture
#

like if its truly a blocking database call, and you need it not to be. well you would need to setup your on thread to run the work on providing its thread safe

coarse charm
brisk pasture
#

then you can use the Tasks to represent work happening on that thread

jolly token
#

I was just going to say "doc is being a Google that collects analystics data for their service"

brisk pasture
#

now it is not too hard to setup your own TaskFactory and TaskScheduler that runs work on its own Thread providing all calls in it are threadsafe

undone coral
#

as an example of how elegant the API is

brisk pasture
#

never used that lib, just was talking about standard library ways to do it

#

though looks pretty smooth for one offs

#

though think i would toss the BlockingIO call in a try/finally, that way 1 exception does not prevent it from switching back to the MainThread

undone coral
#

it will be peaceful

undone coral
#

in the context of a specific RPG? what are you authoring?

#

a conventional baulder's gate style RPG?

#

when you say "level changes" what do you mean?

#

hmm okay

#

are you asking how to express waiting for a long time, in code for example, so that it looks like the quest text?

#

this is a good thing to want

#

so if your quest sounds like

Find the Dragon and slay it.
Return its tongue to the Mayor.

you want code that looks like the english words? because quests are already algorithmic / procedural?

#

you're saying "level changes"... i think that's sort of a whatever concern

#

do you just replace the scene based
replace a Scene? or a scene?

#

what do you mean

#

focus on what i'm asking for a sec

#

do you mean replace the scene as in loading a new unity scene? or do you mean metaphorically replace the scene?

#

it's just important to use the right words you know, when you ask these questions

#

and people who ask questions on the unity code channels... they have different experience levels and say the wrong words sometimes, is all

#

it sounds like you mean an actual unity scene

#

Currently I'm trying to use visualscripting for making a graph
this is probably a bad idea too

#

so is using conditions, and all this stuff in the inspector

#

i don't think you should use Scenes, but that's a different story

#

i'm trying to help you see things in a clear way, which is that there's this long running Task - c# doesn't have such a thing really

#

where you are awaiting things to happen

#

because that's what the quest text looks like

#

?

#

hmm it's too bad this was an interesting question. i think you can use a long running Task

#

i think the core issue is that you don't see things like the quest text as procedural/algorithmic

#

you didn't know that's what it was

jolly token
#

Is this dialogue tree type thing

undone coral
#

dialogue trees kind of suck

jolly token
#

What part are you having problem with?
Making the system? Managing the data? Populating event?

undone coral
#

like people who write well don't use dialogue trees

#

they prefer Ink

#

something that looks like screenplays

#

and then, if you know how ink really works internally, it's a great insight into how to make quests - really, Long Running Tasks - generally

jolly token
#

Gen Z is coming

undone coral
jolly token
#

They don't know what ink is

undone coral
#

ink's engine is, a Task that replays up to where you left off

#

what people want is Serializable Task

jolly token
#

I want that

jolly token
brisk pasture
#

ah have done similar things, where i have game actions and stuff tied into the loc files, so stuff can trigger in certain dialog

undone coral
#

so for example

Find the Dragon and slay it.
Return its tongue to the Mayor.
async UniTask DragonQuest() {
 var dragon = FindNpc("The Dragon");
 await dragon.DiesAsync();
 var player = GetPlayer();
 await player.inventory.OnItemOwnedOrAddedAsAsync(FindInventoryItem("Dragon's Tongue"));
 var mayor = FindNpc("The Mayor");
 await mayor.inventory.OnItemOwnedOrAddedAsAsync(FindInventoryItem("Dragon's Tongue"));
 player = GetPlayer();
 player.gold += 100;
 player.xp += 1000;
}
jolly token
#

Generally I put them in the spreadsheet with conditions that can happen and actions to do πŸ˜…

brisk pasture
#

it very heavily depends on the game and its setup

undone coral
#

if you look at the internal scripting system for RPGs, they tend to look like what i wrote there

#

with the idea being that you can remember where you were along the way of that Task

#

the state of that Task gets serialized

brisk pasture
#

last time i had to do it, steps of a quest where setup using a Command pattern

undone coral
#

it is hard to do that generally, but not troublesome to do it within the limitations of a game

brisk pasture
#

so it was easy to save state changes from each one taking place

#

and revert any if needed

undone coral
#

@jolly token i believe the simplest way to do it is to store a "save point" integer that increments for every side-effectful method call, like player.gold += 100

brisk pasture
#

the actually tracking part is just a statemachine per quest

undone coral
#

in some way

#

you can do it informally or formally

jolly token
undone coral
placid jacinth
undone coral
#

that is passed a container for state

#

kind of like how react works actually

brisk pasture
#

really feel trying to shove await syntax into this problem just makes it harder to follow and debug

undone coral
#

and absolutely none of this other shit does

#

anyway i am just trying to do, the formal version of what really big RPGs do

#

they have a scripting language that is the same energy

brisk pasture
jolly token
#

Just restoring state part is not easy and can be messy
I guess it's like DB migration in a term

brisk pasture
#

why i like the idea of things effecting state that needs to be restored using command pattern

round wharf
#

How would i load a c# dll at runtime (il2ccp game)

jolly token
undone coral
# jolly token Hmmm Yeah this could be somewhat generic

yeah a few approaches

class Quests : MonoBehaviour {
 void Start() {
  // slay the dragon
  GameController.instance.data.AddQuest(async context => {
   // method sets context.Quest variable and other things
   await UniTask.WhenAll(context.player.level.Where(lvl => lvl >= 8).First(),
              context.player.visitedRealms.Any(realm => realm == "Dragon's Realm"));
   // mix animations, rules, dialogue. all in one place
   // why not!
   await context.StartQuest();
   
   var dragon = context.FindNpc("The Dragon");
   if (!dragon) {
     context.EndQuest();
     await UIController.instance.ShowToast("The dragon has already died")
     return;
   }

   await dragon.Killed().FirstOrDefault(evt => evt.Killer == context.player));

   await context.Effect(async () => {
     // do some animations ghost animation
     await dragon.transform.DOMove(new Vector3(...));
     // give the player gold
     context.player.gold += 1000;
     // do an analytics event
     GoogleAnalyticsV4.Event({,,,});
   });
  });
 }
}
undone coral
# jolly token Hmmm Yeah this could be somewhat generic
class Quests : MonoBehaviour {
 void Start() {
     // slay the dragon
     // reactive
     var dragon = context.FindNpc("The Dragon");
     var dragonDied = dragon.Hp.Select(hp > 0).Pairwise().Select(pair => !pair.CurrentValue && pair.PreviousValue);
     var dragonKilledByPlayer = context.player.Kills.Where(k => k == dragon);
     var playerLevel = context.player.level.Where(lvl => lvl >= 8);
     Observable.CombineLatest(dragon, dragonDied, dragonKilledByPlayer, playerLevel)
       .Select((a,b,c,d) => a && b && c && d)
       .Where(shouldFire => shouldFire)
       // extension method that doesn't take if you've already taken this once
       // during htis playthrough
       .TakeOnceInPlaythrough("slay the dragon quest")
       .Subscribe(async _ => {
         await dragon.transform.DOMove(new Vector3(...), cancellationToken:token);
         context.player.gold += 1000;
       })
       .AddTo(this);
  }
 }
}
#

@jolly token lots of ways to skin this cat

#

in the first example you'd need to use methods on the context or a custom async executor to increment the "step counter" of the serializer for the task

#

the positive is that it is really easy to read and debug

#

in the second example you don't need to do that, it can be stateless, but it is way more complicated

#

just like react it would rerun the quest every time anything in it changes

#

and that is also hard to implement

#

the second one might as well just be a subscription to a reactive thing

#

like rxjs wasn't in React's vocabulary

#

i might as well have just done an observable

#

it isn't doing anyhting for me to do it the react way

#

it would make things harder

jolly token
#

Let's make it modular and decoupled and serializable 😌

#

Rx is neat for UI but I feel like it's becoming Perl

#

"Write once, read never"

undone coral
#

yeah i fixed the example

#

it wouldn't be that hard for multiple step things in observables

#

it would be "ContinueWithPlaythroughSavePoint("you found the dragon")"

#

if that makes sense

#

or really

#

Observable.TakeMemoized(..., "a name for this checkpoint")

#

what do you think

#

i think the first one is more powerful

#

but really hard to implement

jolly token
#

Thing is when a designer implement this

#

They have to understand where to save and what to consider

undone coral
#

designer would want context. then autocomplete gives them all the options

#

yeah

jolly token
#

And I don't trust designers

undone coral
#

that would only be possible in the first case

#

the designer isn't going to come up with an animation

#

someone else will do that

jolly token
#

That too πŸ˜„

undone coral
#

i personally like to be able to author Timeline content in code

#

so that's why i think it's important to have #1, it makes it easier to add in animations, dialogue, UI effects, etc.

#

and just messing with game objects

#

these are the two approaches that can make these things very robust / low bugs

#

but only the first approach really looks like the text of the quest

jolly token
#

And that's a good thing yeah

undone coral
#

no i never write tests for unity

#

someone i'm sure has tried to do serializable tasks

#

in java i used a serializable fibers library but never serialized anything

#

wasn't necessary

#

i think akka can also serialize actors

#

very Erlang

#

it is nice to be able to just declare a variable, side effects be damned

#

if you wrap side effects in context.Effect(() => {}) you can do it

jolly token
#

Hmm only if we can just jump in to middle of Task

undone coral
#

it's like writing haskell

undone coral
#

it kept a program counter

#

and leapt through the block points

jolly token
#

Maybe possible in world of pure function

undone coral
#

so if you deserialize a fiber, it (1) restored all the scoped variables and (2) skipped all the code up to the save point

jolly token
#

Isn't versioning gonna be very challenging for that?

#

Like how do you even modify code with it πŸ€”

undone coral
#

it's only possible to restore a previous version if the variables (local, closure) stay the same

#

but that's true in the RPG script code too

#

i wonder how those RPGs migrate for patches

#

probably jsut declares a "migrate" method

jolly token
undone coral
undone coral
#

that's the Lispy way to do it

jolly token
#

tHaT's NoT pReTtY

undone coral
#

very cheap

#

yeah i know

#

but in my example it would work

#

and you wouldn't need a degree in CSharpology to pull it off

#

you would just hijack await

#

which you can do

#
...
Task Effect(string name, Action<T> action) {
 // internal
 Context.current.SetEffect(UniTask.Run(() => {
  if (Context.current.HasExecuted(name)) { return; }
  await action();
  Context.current.SetExecuted(name);
 }));
}
#

there is a C# api that looks like this

jolly token
#

Hmmm right

#

Just wrap that think with class then it can be generic something

undone coral
#

^ something like that. SetExecuted would write to your save file

#

could be even simpler

#

skip the action if the save file shows it was executed

#

whaddya think?

#

this is if you're rerunning the whole function

#

in a language that cannot guarantee purity

#

= bugs

#

i would rather allow it to be impure but use a custom async executor

jolly token
#

The things that really irritating would be exception handling

undone coral
#

exceptions? who makes those

#

lol

jolly token
#

In general term lol
For example you give user a 500 diamond for initial draw
And you do the draw, but the game crashed

#

Hmm no you send server call and game crashed

#

Now the diamond is gone and your Task is deadlocked

undone coral
#

yeah

#

server call would be impure

#

i am not familiar enough with haskell

#

to say how it Deals

#

but there's an approach

jolly token
#

Monad?

undone coral
#

not

#

sure

undone coral
jolly token
#

Only if C# let us overload >> without constraint

#

We could do monad with pretty >>=

undone coral
#

lol

#

that is essential

#

when i think language features, i think, shit we need an operator

jolly token
#

Like when C++ developer became so excited and made std::cout

#

That's probably why C# banned overloading >> without int param

#

beginning with C# 11, the type of the right-hand operand of an overloaded shift operator can be any.
OH shit dream comes true

wet burrow
#

Something is seriously wrong with my while loop. You can see the array has a length of 14 and it's supposed to destroy 2 objects and have a length of 12 by the end. But while it's reduced by two, the loop only runs once and only one of the objects is destroyed.
https://cdn.discordapp.com/attachments/377316629220032523/1021997202899480627/unknown.png
https://cdn.discordapp.com/attachments/377316629220032523/1021997203260178502/unknown.png
The only explanation I can think of is that one of these functions is somehow also removing an entry from the array, so it runs twice in one loop while only destroying one object.

jolly token
wet burrow
#

@jolly token the object is a Toggle (as in the regular UI component)

#

it says there

#

hang on I oughta double check

#

hang on it might be a ToggleGroup thing

flat marsh
#

Does by chance the second object have the same name as the first und you have collapse on in the console?

wet burrow
jolly token
#

some editor flexible enough to copy-paste (not exactly, will always need small edits but) it into different projects and easy enough to use by dudes who cannot into programming.
Excel! πŸ˜„ https://github.com/cathei/BakingSheet

jolly token
#

This also sounds like anti pattern my friend.
First, you are relying on static states (FindObjectsOfType*)
Second, it is still hard to refactor things and track references
Third, how would you handle dynamic object that instantiated?

#

I think he meant what he wrote- since it is suggested as replacement of singleton

brisk pasture
#

really, its unity is just a pain in the ass with this, since you do not control object construction directly for most things

#

and do not have just 1 entry point

#

being too strict about any approach is just asking for headaches

jolly token
#

That would be the root of the problem 😌

brisk pasture
#

but i often end up with a service locator, that lets me request objects registered to it by type, and lets me easily swap those implementations out

#

in literally everything else i do that is not Unity, this problem is fully avoided, since i control object construction and what order things are constructed in, so pretty easy to do dependencies first, and pass them down as constructor args

maiden turtle
#

or rather ranges

jolly token
#

I wonder, maybe service locator is better pattern for Unity as they aligns with GetComponent series πŸ€”

jolly token
#

C++ has it all

maiden turtle
#

meh, di is better

#

and it also could handle dynamic objects

jolly token
#

It’s not the problem with using API. You are getting your states from static states without context, that’s not flexible enough IMO

I’d prefer generic solution like DI really. With this I’ll have to write lots of ad-hoc code to handle state and context properly.

I guess you can just go with ECS pattern if you prefer

orchid marsh
#

di, referring to dependency injection?

maiden turtle
#

yes

#

aka passing dependencies on intitialization

#

you'd make an interface for invoking that event and just initialize the thing doers with a reference to the implementation when you create them

#

how you're going to pass that reference is your choice

#

you can do every object individually in a test

#

passing in a mock

#

you can use a di container

#

you can access a static singleton instance

#

di is more dynamic in this sense

#

but if you have a framework than it would likely use reflection and bind it automatically from its container

#

I instantiate everything manually

#

zenject does reflection to bind the dependencies

#

you'd have an initialization method, and it would bind the objects according to some rules that you define

#

but you still have the choice to initialize any object manually

#

I just have an initialization routine where I initialize everything explicitly

#

If I needed dynamic objects that have dependencies, i'd create a factory, explicitly

#

Might be more code and somewhat clunky, but the good thing is that there's no magic involved

maiden turtle
#

look at how zenject works, or check out di in aspnet core

#

essentially, its just an initialization method for you monobehaviours

#

and passing in the dependencies

jolly token
#

How is it advocating singleton? Using singleton with DI is compeletely fine because the fact that it is singleton is hidden, you can always refator or swap the implementation

brisk pasture
#

you are just being pandantic about it, its fine to have a few if they save you from other problems

jolly token
#

Your example is also a singleton as only single instance would exist. The problem is not singleton, the problem is β€œsingleton pattern”

#

Btw my DI container impl does not use singleton anymore since I refactored it

brisk pasture
#

think you are way more concerned with what you call "good code" then getting stuff done then

#

like having 1 object as a locator or a di container that is singleton is fine

#

more then fine, since it provides 1 entry point where dependencies for runtime or test can easily be setup

low mesa
#

Hello everyone!
We are facing a rather odd issue, and we are unable to solve it so far.
Here is the situation:
We have a few packages imported into our game project, and one of them is
"collections"
2 of our components are relying on this package, but one of them is looking for 1.0.0, and the other one is looking for 1.2.0.

We don't have any problem until we try to build, no error msg nothing, but the build can not be done.
How can we segregate the 2 packages, or what other options we have?

We need both component to be working.

jolly token
#

That’s fine, debating for better design is a good thing

brazen hamlet
#

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.W))
        {
            reducedHP();
        }

        if (Input.GetKeyDown(KeyCode.E))
        {
            Noway();
        }
    }
    public void reducedHP()
    {
        healthpoints--;
        if (healthpoints < 3)
        {
            SecondPhaseStarts?.Invoke();
            FirstBoss.SecondPhaseStarts = null;
        }
    }

    void Noway()
    {
        healthpoints++;
        if (healthpoints > 5)
        {
            FirstBoss.SecondPhaseStarts = null;
            SecondPhaseStarts?.Invoke();
        }
    }``` 

On "SecondPhaseStarts.Invoke". basically when this object reach below 3 on its healthpoints, the other gameobject from another script that subscribe to this event has stop spawning. When it's more than 5 healthpoints, it respawns. It works! 

BUT, when i made the healthpoints below 3 again, it still spawns and didnt stop. pls advice? 😦
undone coral
#

it sounds like you have a complex project

#

2 of our components are relying on this package, but one of them is looking for 1.0.0, and the other one is looking for 1.2.0.
this doesn't really matter. they will just both use 1.2

#

it doesn't work like npm, this is a red herring

#

how do you know you aren't building? what is actually happening?

low mesa
#

@undone coral
Thank you for the reply!
Yes indeed it's a complex project. Atm we trying to implement Singular (the analytic tool) and it causes this problem. Let me grab the msg we get during the build process.
(actually one of my co-worker making it, will ping you again in a bit)

undone coral
low mesa
#

but if we don't have the Sing. in: we all good.

undone coral
#

i'm sort of stating the obvious here but why don't you contact them

#

nobody has any experience with installing this obscure thing delivered as a unitypackage

terse bobcat
#

does anyone have an ide how to add a decent camera shake while running

sturdy edge
terse bobcat
low mesa
# undone coral i'm sort of stating the obvious here but why don't you contact them

We did. Not much progress so far (2 days...)

This is the package problem that I have mentioned

  • What went wrong:
    Execution failed for task ':launcher:checkReleaseDuplicateClasses'.

1 exception was raised by workers:
java.lang.RuntimeException: Duplicate class androidx.collection.ArrayMap found in modules collection-1.0.0.jar (androidx.collection:collection:1.0.0) and jetified-collection-1.2.0.jar (collection-1.2.0.jar)
Duplicate class androidx.collection.ArraySet found in modules collection-1.0.0.jar (androidx.collection:collection:1.0.0) and jetified-collection-1.2.0.jar (collection-1.2.0.jar)
Duplicate class androidx.collection.CircularArray found in modules collection-1.0.0.jar (androidx.collection:collection:1.0.0) and jetified-collection-1.2.0.jar (collection-1.2.0.jar)
Duplicate class androidx.collection.CircularIntArray found in modules collection-1.0.0.jar (androidx.collection:collection:1.0.0) and jetified-collection-1.2.0.jar (collection-1.2.0.jar)
Duplicate class androidx.collection.ContainerHelpers found in modules collection-1.0.0.jar (androidx.collection:collection:1.0.0) and jetified-collection-1.2.0.jar (collection-1.2.0.jar)
Duplicate class androidx.collection.LongSparseArray found in modules collection-1.0.0.jar (androidx.collection:collection:1.0.0) and jetified-collection-1.2.0.jar (collection-1.2.0.jar)
Duplicate class androidx.collection.LruCache found in modules collection-1.0.0.jar (androidx.collection:collection:1.0.0) and jetified-collection-1.2.0.jar (collection-1.2.0.jar)
Duplicate class androidx.collection.SimpleArrayMap found in modules collection-1.0.0.jar (androidx.collection:collection:1.0.0) and jetified-collection-1.2.0.jar (collection-1.2.0.jar)
Duplicate class androidx.collection.SparseArrayCompat found in modules collection-1.0.0.jar (androidx.collection:collection:1.0.0) and jetified-collection-1.2.0.jar (collection-1.2.0.jar)
--

#

I was wondering, maybe we could just segregate the 2 packages with namespaces maybe? Or any other way to do that? Because as far as I can see the problem here is the fact that we have 2 of the "kinda" same packages.
If I could separate singular's stuff, from the others... could that work?

undone coral
#

i mean you said collections package, i had no idea which package you meant, and here you clearly have an error message

#

and you're talking about an issue with the android build

#

it sounds very complex for you

#

you should wait for their response

jolly token
flint sage
#

Bigint?

jolly token
# flint sage Bigint?

It'd be too big and slow. I don't need that much of precision, I want more of incremental-game kinda number

#

They are not deterministic since they are using double under the hood, that’s why I’m finding something else

#

Because I need deterministic calculation across platform?

sly grove
#

or maybe:

int hundredths;
int exponent;

Such that:

hundredths = 534;
exponent = 7;

Would indicate:
5.34 X 10^7

#

you'll have to write all your own arithmetic functions with this but it should work for what you need and be deterministic.

compact ingot
jolly token
jolly token
compact ingot
#

What exactly is your issue with a regular double?

#

best option if double doesn’t work is to just duplicate any other floating type implementation with a custom exponent size

sly grove
#

I think floating point is the problem in the first place

#

because the math is not deterministic across hardware

#

it needs to be deterministic fixed-point arithmetic. Although the use case hasn't been shared actually...

compact ingot
sly grove
#

right - don't try to get deterministic floating point math. Do fixed point math instead!

jolly token
#

I’ll just say that I need to run input synced simulation (e.g. lockstep) with incremental stat number πŸ₯² I guess I’ll have to implement custom type

haughty sun
#

is Dear IMGUI used in the industry for unity?

sly grove
haughty sun
#

that shit giving me nightmares

#

I was making a imgui console for development but i realized the package doesnt work good as i supposed, don't wanna code it unity's own either...

brisk pasture
#

i would not say a port, but yeah its a IMGUI so heavily inspired by dear imgui

#

i really do not mind IMGUIs for tools

timber flame
#

Which one do you choose?
Find the shortest path from a source point to several target points (specific type of a tile)
a--> (b1,...,bn)
Output: a--> bm
1- Dijkstra
2- A* for each target point

brisk pasture
#

the 2 things are almost the same

#

just easier to influence A* into working in slightly different ways

sly grove
brisk pasture
#

also if 3d or working on the xz plane i would just let unity do it for you

timber flame
brisk pasture
#

its A* on a navmesh

timber flame
#

I want to know which one is faster you guess

#

Run A* for each target point or Dijkstra

sly grove
#

otherwise it's slower or equal to djikstra

brisk pasture
#

A* with the right hueristic will check less nodes

timber flame
#

Because that tile exists in many positions. So, there are many target points

sly grove
#

both algorithms find the shortest path to all nodes or specific node depending on how you write/configure it

brisk pasture
#

alot of the optimization for both of them will come down to proper data structures for the open and closed sets

#

and reducing the amount of nodes

timber flame
#

I think classical A* works with one target point!

brisk pasture
#

what are nodes in your case

sly grove
#

Both algorithms work with one target point

brisk pasture
#

grid tiles, a quad tree like thing or triangles?

timber flame
#

I don't know what you mean

#

Dijkstra's algorithm (/ˈdaΙͺkstrΙ™z/ DYKE-strΙ™z) is an algorithm for finding the shortest paths between nodes in a graph

#

So, it does not have one target point

#

finding the shortest paths between nodes

#

It creates a matrix [v,v]

honest hull
#

Hey so if I have a .asset file
how do I extract the mesh for it so I can modify it(change its index's from 16 bit to 32 bit) and save it back to the asset file?

sly grove
#

it's literally the same algorithm as A*

#

with one fewer function call

#

I've written it in college (10 years ago but still)

#

it builds a matrix for memoization purposes

timber flame
#

I have implemented it 15 years ago as well

sly grove
timber flame
#

see wiki

sly grove
#

hmm strange
how the wiki is showing it being used to find the shortest path between two particular points

timber flame
#

Dijkstra doesn't use heuristic

#

A* does

sly grove
#

that is the only difference

brisk pasture
#

heuristic is just the hcost function added

timber flame
#

to go to the next

sly grove
#

if you stop it when it finds the point of interest

#

then you're fine

#

The difference with A* is you need to start with a goal node in miond in order to have a hueristic function oriented toward that goal

#

that's the only difference

timber flame
#

yes, but A* classic heuristic is only for one target point

sly grove
#

yes

timber flame
#

it does not work with multiple at all

sly grove
#

right

#

well acutlaly

#

it DOES

#

but

#

the hueristic just becomes useless

#

that's all

#

you can let it keep running after finding the target node, just fine

brisk pasture
#

its also easy to just but it on a flag and disable that one added feature

timber flame
sly grove
#

I guess given what you're actually asking here

#

djikstra is most likely more efficient since a lot of work won't need to be repeated. But you could also just modify A* somewhat and have it re-use the costs calculated in previous runs just fine

#

modified A* would be fastest probably but simpler to just run djikstra until you see all your targets.

#

I am working on a similar project - tower defense game - where I precompute all the shortest paths up front

#

and have all the enemies just follow those precomputed paths

#

ultimately the performance ends up not mattering that much if you can precompute the paths and reuse them.

#

Which may or may not be applicable to your game

timber flame
#

1- Choose n closest target points (n-nearest search)
2- Sort them by distance
2- Run A* for the closest one
3- After reaching, remove that target point and repeat
I think it is OK

timber flame
sly grove
#

I do the pathfinding recomputation when the player changes the grid

#

but that happens in a separate phase from the enemies moving around

#

not sure how yours works

brisk pasture
#

depending on the unit count and other factors, maybe want to look into more specialized approaches like what a rts game with high unit caps would do

sly grove
#

At some point on the spectrum from "finding shortest path from a to b" to "finding shortest path from a, b, c, and d to e, f, g, and h" I went from using classical Djikstra/A* to more or less just using Breadth-First-Search and doing lots of memoization and it went better.

gray pulsar
#

@timber flame you could also modify A* and/or Djikstra to pass in the heuristic and end condition as delegates, rather than having them hard coded as a target node + distance function to that node

#

not sure how bad that would be for performance, though

timber flame
#

but now, we want weighting/priority

brisk pasture
#

seen some approaches where instead of working the path backwards from destination like you do in A* or Dijkstra's, where it processes it all and saves directional vector information in each tile

sly grove
#

i call them signposts

#

the AI just follows them

brisk pasture
#

yeah supreme commander does a approach like this

gray pulsar
#

like flow field pathfinding

timber flame
#

Storing the direction

brisk pasture
#

why i mentioned it depends on your unit cap

#

its way more expensive for only a handful of things following

sly grove
#

yeah so you need to weigh your write/read ratio basically and decide if the cost to create them is worth it. In my game I have hundreds or thousands of enemies that all reuse the same paths so it's absolutely worth it

brisk pasture
#

but if you are getting into hundreds of path followers

sly grove
#

if your graph changes a lot, the cost to create them may be too high

gray pulsar
#

also depends on whether your units are navigating to the same place or different places. If everyone is going to the same destination from different origins, flow field can be really efficient

brisk pasture
#

really i just use pretty basic A*, but i made my data structures as effecient as possible, and reduced the amount of nodes as much as possible

#

also run it on its own thread

sly grove
#

as long as the number of units reusing the field is high it can be worth it

brisk pasture
#

using a mesh or quad tree really cuts down on the node count

#

over evenly spaced grid

#

and A* and Dijkstra's do not care what the data is, as long as you can get your neighbors, and the more convex space you can represent with 1 node the more you can rely on stuff like local avoidance while also reducing the amount of nodes that need to be considered even for getting costs for every tile

umbral nimbus
#

Hey guys, I'm trying to get this system of re-orienting a 2d isometric object to work. It works by containing 4 sprites of the same object in each cardinal orientation packed onto the same GameObject.

The problem is, the update function doesn't seem to work:

    public void setOrient(int orient)
    {
        tiles[this.orient].color = Color.clear;
        this.orient = orient;
        tiles[orient].color = Color.white;
    }
#

When I run this code the tile stays transparent

chilly nymph
umbral nimbus
#

yes

chilly nymph
#

I don't see it.

umbral nimbus
#

Color.clear is (0,0,0,0)

#

Color.white is (1,1,1,1)

chilly nymph
#

Sorry I didn't know the enum supported lower cases.

#

Debug to check if you're on the right tile?

umbral nimbus
#

sure, hold on

#

yeah pretty sure that's the right tile

chilly nymph
#

I mean in code.

umbral nimbus
#

oh

chilly nymph
#

tiles[this.orient].color could be referencing a null?

umbral nimbus
#

ah. Pretty sure that isn't. Because it's referenced in the start() function

#

and it doesn't throw a NullReferenceException

chilly nymph
#

Drop a bp

umbral nimbus
#

bp? Sorry, I must be terribly new at this

chilly nymph
#

Breakpoint.

umbral nimbus
#

ah

#

ok

#

ok. So I just figured out how to debug mode. Thanks

#

hmm, I'll fiddle with it on my own for a while. Don't want to eat up too much of your time.

grave vortex
#

how can I replace the skybox material in a custom render feature?

#

I need to sort this out.

bronze geyser
#

Is there a way to declare a vertex on a mesh as an "anchor" and reposition the mesh relative to said anchor point?

#

I've way too many hours trying to position this procedurally generated mesh and my everything hurts

lament salmon
bronze geyser
#

Oh, that would make the anchor position 0,0,0

#

That makes sense

#

Excellent

#

Thank you ❀️

craggy spear
#

This is a code channel, for advanced code questions. Delete from here and ask in #πŸ’»β”ƒunity-talk - though you'll be better off posting on the forums with that question

flint wraith
#

Hello, have question, trying to implement creating of scriptable object with inheritance yet unity doesnt know what to do.
Anybody tried something like this? What am I doing wrong

#

Error happens when i create scriptable object and try to drag it to object with Test script

fresh salmon
#

What's the file name where class HelmetSO is declared?

flint wraith
#

@fresh salmon all files I have

fresh salmon
#

When you select the HelmetSO file in Unity, and look at the Inspector, do you see the code or not?

flint wraith
fresh salmon
#

Setup looks good to me

flint wraith
#

yeah, i did initially put everything in Test script and split them after error into these files, but refresh should have handled that.
maybe some reset unity functionality to rebuild it?

fresh salmon
#

Yeah, it's weird that it says "None" on the SO instance file

#

Delete the SO (not the instance, the class itself) and re-create it to force a complete rebuild

flint wraith
#

Yeah, it fixed the problem, thanks hahahahah

hot lintel
#

I am trying to add the burst compiler to Unity 2019.4
I downloaded the "2019.4 Verified" package, and I get 5 errors. Each of them are the same but for different systems.
Basically it complains that I don't have XboxOne, XboxSeries and PS5 in my list of build targets.
Library\PackageCache\com.unity.burst@1.7.4\Editor\BurstAotCompiler.cs(259,47): error CS0117: 'BuildTarget' does not contain a definition for 'GameCoreXboxOne'
Does anyone know what version does not have this problem?
Because it's quite silly it's "2019.4 verified" yet requires build targets I am not actually going to build for

wide loom
#

When using INetworkSerializable is there any difference between doing it these 2 different ways (examples are different structs)?

 public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
        {
            serializer.SerializeValue(ref firstname);
            serializer.SerializeValue(ref lastname);
            serializer.SerializeValue(ref number);
            serializer.SerializeValue(ref heightScale);
            serializer.SerializeValue(ref widthScale);
            serializer.SerializeValue(ref speedScale);
        }

or this

public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
        {
            if (serializer.IsReader)
            {
                var reader = serializer.GetFastBufferReader();
                reader.ReadValueSafe(out name);
                reader.ReadValueSafe(out color);
                reader.ReadValueSafe(out logo);
                reader.ReadValueSafe(out players);
            }
            else
            {
                var writer = serializer.GetFastBufferWriter();
                writer.WriteValueSafe(name);
                writer.WriteValueSafe(color);
                writer.WriteValueSafe(logo);
                writer.WriteValueSafe(players);
            }
        }
#

The first seems cleaner and shorter, why would some examples do it the second way?

hot lintel
#

What if you don't wanna work with refs?

wide loom
#

Is there a reason you would not want to use refs?

hot lintel
#

A ref is not always desirable because of mutability.
Some times you want to keep things local, other times you want to work with references.

#

It really depends on your use case I'd say.

gentle topaz
#

good APIs leave the lower level options open for people who have very specific needs

hot lintel
#

☝️

#

In most cases you'll never actually need to use ref

#

It has some nice use-cases, but it's rarely actually needed

pulsar tundra
#

Hi, is there a reason my Quaternion only produces half of the required rotation here?

flint sage
#

Why are you trying to construct a quaternion manually

pulsar tundra
#

Because every solution I've tried for my problem results in Gimbal lock, or undesired rotation

digital helm
#

Has anyone used babylonjs?

#

I'm trying to figure out how to convert the angles of the camera there into unity

#

Looks like Z there is facing the other direction

#

but can't seem to figure out how to convert the angles

#

any help would be greatly appreciated

brisk pasture
#

@digital helm would need to figure out what the up and forward axies are

#

then also if its left or right handed coord system

sly grove
#

what are you trying to do

pulsar tundra
#

I've tried lots of diff things, AngleAxis makes the rotation bug when the Axis changes, using Dot makes the character spin like that when the Vectors are completely opposite

sly grove
#

that's pretty vague

#

what's the "tether point"? Is that where the rope touches the platform?

pulsar tundra
#

so the play should be able to hang parallel to the rope attaching it to the tether point which is where it intersects with the platform

#

so it needs to rotate on X by Vector3.right and Y by Vector3.forward

#

and then if I try to get the Angle from 2 Vectors, when I combine the rotation it's just completely wrong

undone coral
#

ref Quaternion currentRotation and constructing your own Quaternion suggests that there are

#

so many bugs

#

that some of them are interacting together

#

to produce positive (expected) effects

#

so it's going to be a lot of back and forth of us saying "well what if you fix X in your code" and you're going to say "no that breaks Y"

#

"i just want this to Z"

#

AngleAxis makes the rotation bug when the Axis changes, using Dot makes the character spin like that when the Vectors are completely opposite
this is because there are so many bugs, changing any one thing in isolation breaks some unintended interaction

pulsar tundra
#

alright np

#

ill figure it out im sure

undone coral
#

basically your code is this scene in the Simpsons right now @pulsar tundra

pulsar tundra
#

just been stuck on this for so long

undone coral
#

there are so many bugs they are in perfect balance

#

@pulsar tundra well you can always rewrite things

#

programming isn't VFX, you can't just tinker and layer on things until it works and then you ship it

#

it sounds like you want to have a 3d game where characters tether to a platform and swing around it

#

and you have a specific opinion of how the tethered versus untethered (free fall) behavior should be

#

@pulsar tundra if you want the tethering to behave naturalistically, you can use the physics engine to get this effect

#

would you describe the desired behavior as "naturalistic"?

digital helm
#

not 100% sure how to check the forward axis tho

#

but i think its Z

pulsar tundra
undone coral
#

in the video you shared, you're showing a character moving about a tether point

#

i can see why you're using the word rotate

#

but there's rotation and rotation, you know what i mean?

#

are you trying to make the character move naturalistically by moving the character around the surface of a sphere centered on this tether point?

#

or do you want Physics to do that for you? @pulsar tundra

#

it isn't clear from your code or your words what you want

#

do you want to orient the player model a certain way?

#

the code snippet doesn't tell us, and you haven't told us

#

so we're confused

pulsar tundra
undone coral
#

there's physics and then there's Physics

pulsar tundra
#

yeah I get that

undone coral
#

so why aren't you using Physics to do that?

pulsar tundra
#

well im using an Asset for the character controller like you said

undone coral
#

okay

undone coral
#

the tether point is the center of my sphere, the length of the tether is the radius of the sphere - it looks like we're assuming the tether is of a fixed length / rigid, which is fine

#

i would draw a vector from the center to the player's current position. then, i would rotate that vector by a small amount: the angular velocity * Time.deltaTime, whose units work out to be a small amount of rotation.

#

that's pretty much it

#

the resulting vector is the new position

#

as soon as the tether is disconnected, i would transfer the angular velocity into Physics velocity

pulsar tundra
#

right I see

undone coral
#

i would not express angular velocity as tangential velocity

#

as soon as the tether is connected, i am assuming the tether is 100% rigid, so i will assume that the amount of linear momentum that gets turned into "angular" momentum (angular with respect to how i am simulating this, which is the rotation of a big sphere)

#

looks something like

angular velocity = Vector3.Cross(tether vector, velocity) / (length of tether squared)

#

this will correctly result in a lower angular velocity of this big rigid sphere i am rotating

#

if the tether is longer

#

is this helpful?

pulsar tundra
#

yes this helps a lot thankyou

undone coral
#

you got really into the weeds i think with the code you already have

#

so the gist is

#

when my tether connects, transfer all of my momentum into the rotation of a big giant sphere centered on my tether point

#

and we are solving for angular velocity in the equation

tangential velocity = (angular velocity) W cross (position of point on this sphere) R
tangential velocity = instantaneous particle velocity at moment of tethering V

pulsar tundra
#

okay that makes much more sense now

undone coral
#

i wouldn't describe this as physical

#

it is sort of naturalistic

#

it's really very gamey

#

but based on the video you shared that sounds like it's what you want πŸ™‚

#

imo, you should actually place a rigidbody into the scene that models the sphere

#

whose mass is the player's mass

#

or whatever

#

and actually transfer the momentum

#

and this way you can still do it with Physics

pulsar tundra
#

okay yeah I'll give that a go too

undone coral
#

with the right collision layers it will work πŸ™‚

#

you can also... do the actual tether

#

but it sounds like you don't want totally physical behavior

#

an actual rope would behave weirdly*

#

even this approach will behave surprisingly sometimes

#

like if you have a very small angle between your current velocity and the moment you connect the tether

#

in real life, the rope would bunch up

#

in this, you will suddenly go into a sphere moving very very slowly

pulsar tundra
#

yeah I have an idea for some things like at the top of the swing I cancel out Velocity so that the player falls with gravity

#

i can do that now

#

just tryna get this rotation part down coz im so confused

icy aspen
#

I have a problem, im making a game thats currently on webgl, i want to show touch controls only when the player is playing on mobile, but not when the player is on pc or something else. How can i do this?

sly grove
#

I also think it would be a good idea to give the option to use touch or not when available because a lot of PCs also have touch screens these days.

west scarab
#

Using the manual nav mesh builder api: Is it fine to use many instance of NavMeshData and adding / removing them from the global nav mesh, or does this have performance implications? I couldn't find anything in the docs

regal olive
#

it works :)

iron urchin
#

I’ve got a question I hope one of you fine programmers can answer. In games that feature procedurally generated worlds, like Minecraft or No Man’s Sky, is the world completely generated at launch and held as data which is rendered only when the player reaches a certain proximity? Or is the creation and rendering happening simultaneously?

iron urchin
regal olive
#

The only general rule about what's possible or not is your hardware and the halting problem

rugged radish
#

both approaches are used, it depends on your goal
those 2 examples use the second approach

iron urchin
lavish sail
#

way too much

regal olive
#

I would use the first approach to eg save it on disk if loading it from disk takes less time that computing it

lavish sail
#

maybe Terraria, not sure though

rugged radish
lavish sail
#

terraria has a lot less to save because the world is 2d and finite

regal olive
#

You also need to generate it full if you need some sort of consistency between each part of the world

#

if some part depends on another then you kind of have no choice

iron urchin
#

So in theory one could generate the world on initialization, saving the mesh and object location data in arrays and sub arrays, storing those on disc, Then allow subroutines to access and alter that data at runtime?

regal olive
#

Yeah but be careful, disk is expansive

lavish sail
#

well if it's optimized enough

rugged radish
#

you probably don't want to save the mesh, but only the data, like heightmaps, biome maps, things like that
and generate the mesh at runtime

iron urchin
#

maybe I am miss using the term mesh. What I mean is the matrix data and world position locations. Is that not just an array of numbers that can be stored and accessed relatively inexpensively? I apologize I know I’m posting in the advanced code section, with admittedly not an advanced knowledge of practical coding.

regal olive
#

Depends what you mean by inexpensively, you can check your disk throughput if you wanna know precisely

rugged radish
#

mesh is basically the 3D model of your world

#

the terrain, specifically

#

in the context of my message

sly grove
#

There are lots of games that generate a relatively small procedural world at the start of a game session and use it for the rest of the game, something like Deep Rock Galactic would be an example of that

#

Or Factorio

#

But Minecraft and No Man's Sky are in a different category - since their worlds are "infinite"

iron urchin
sly grove
#

they aren't actually infinite but the limit is not that there is some world size that was pre-created, the limits are just the limits of the computer to represent numbers accurately.

#

like you have coordinates in a minecraft world on x, y and z. But the world uses floating point numbers to represent those coordinates, which have practical limits as you get too far away from the origin.

iron urchin
#

Ahh. So as the player travels farther, more world is generated, to the point that the data size can no longer be handled.

sly grove
#

something like that yeah

frozen badger
#

Minecraft is like, 5 times the size of the actual earth right

#

No way to store all that, really

sly grove
#

You run into both storage limits and floating point precision limits with minecraft

#

since the generated chunks are actually stored on disk

frozen badger
#

That's why the generator used to go haywire when you reached the higher numbers right

sly grove
#

Not sure I'm familiar with that particular phenomenon

frozen badger
#

since floating point precision falters as you reach certain number

frozen badger
iron urchin
#

Fascinating

compact ingot
frozen badger
#

That's.. a minecraft world is 60 million meters wide

compact ingot
#

to have a map of that size you need to have a moving origin

frozen badger
#

assuming one block is 1m

sly grove
compact ingot
#

the minecraft generator failing is probably just an artefact of their perlin noise implementation that breaks down for large numbers but could be easily avoided by using a 64+ bit implementation

frozen badger
#

I wasn't aware perlin noise had a large number issue

#

isn't it all local

compact ingot
#

wdym local?

frozen badger
#

like, the value of an area is just dependent on the local values surrounding it

compact ingot
#

if you generate a 60mill unit map you sample that noise at x = 60mill and ofc it has float issues there, since you cant represent 60mill accurately in float

frozen badger
#

Yeah, that's what we were talking about

compact ingot
#

but you could just use a higher precision floating point type and be fine

#

or use multi resolution sampling

iron urchin
#

Local as in the range is connected to the neighboring vertices.

frozen badger
#

yeah, so having a four billion wide grid wouldn't make the perlin noise strange

#

like it's not inherent to the algorithm

compact ingot
#

well, mathemateically no, but every implementation will have this problem inherently