#archived-code-advanced

1 messages Β· Page 39 of 1

pale silo
#

question :


            Debug.Log(LocalizationSettings.AvailableLocales.Locales.Count);

you can see in the picture that I have two locales, yet when I debug the length of available locales .. I GOT 0....
(I am trying to change locale, but because the length of locales array is 0 then I always get an error... help please)

raven orbit
#

Is it ok for my MoveController to have a reference to the grid? How can I decouple?

public class GridGame : MonoBehaviour
{
    [SerializeField] public GameObject[,] gameGrid;

    public delegate void GridBuiltCallback();
    public event GridBuiltCallback OnGridBuilt;

    void Start()
    {
        StartCoroutine(CreateGrid());
    }
    private IEnumerator CreateGrid()
    {
//Creates the grid
    }
    
    public Vector2Int GetGridFromWorld(Vector3 worldPosition){
        int x = Mathf.FloorToInt(worldPosition.x/tileSpacing);
        int y = Mathf.FloorToInt(worldPosition.y/tileSpacing);
        
        x = Mathf.Clamp(x,0,width);
        y = Mathf.Clamp(y,0,height);
        
        return new Vector2Int(x,y);
    }
    public bool IsTileOccupied(vector2 int pos)
{
return gridGame[pos.x,pos.y].is occupied;
}
}
#
public class MoveController : MonoBehaviour
{
    private GridGame gridGame;
    public void Move(Vector3 direction)
    {
        if (_isMoving) return;
        if (!CanMoveToTile(direction)) return;
        //MOVE
    }
    public bool CanMoveToTile(Vector3 direction)
    {
        Vector2Int currentGridPos = gridGame..GetGridFromWorld(transform.position);
        Vector2Int targetGridPos = currentGridPos + new Vector2Int((int)direction.x, (int)direction.y);
        return !gridGame.IsTileOccupied(targetGridPos);
    }
}
vocal granite
raven orbit
#

Wait let me fix it

raven orbit
raven orbit
#

Anyone? UnityChanClever

jolly token
raven orbit
#

so no other way around?

jolly token
#

What would be the reason you are seeking for other way?

#

Are you planning to reuse MoveController somewhere outside grid?

raven orbit
#

no

#

I lack the concept of how in depth I can decouple things but I guess it's fine

#

There Is only one player and only one grid in my game so should be fine

jolly token
blissful dagger
#

yo sup guys i have this code which just creates my own mini physics system to check if the player is above any platform, the platforms spawn and move from right to left and the player just jumps in his place, only problem is on low fps the player is jittering on the platform or going in and then getting on the platform how can i fix this?

orchid marsh
blissful dagger
orchid marsh
#

Depends on how you're using velocity. What're you doing with velocity?

blissful dagger
#

just that player.transform.Translate(new Vector3(0, velocity, 0) * Time.deltaTime);

#

does changing to fixedDeltaTime here help?

blissful dagger
#

yeah thought so

orchid marsh
#

You could probably resolve this by doing the platform (ground) check after incrementing velocity instead of before.

blissful dagger
#

I tried didnt work

orchid marsh
#

In the platform (ground) check, you'd have to include velocity with the formula for desired distance as you're about to make a gigantic leap downwards this very frame.

blissful dagger
#

okayy will try thanks!

orchid marsh
#

Or rather, diffY + velocity.y < ... @blissful dagger

#

Something of the sort

blissful dagger
#

the crazy thing that happened is translating then checking for the rest worked just fine i think because the player has to have a velocity of 0 at the start so no problem with unitialized values but thats really weird

#

im sure i missed something lol

orchid marsh
#

Regardless of what's occurred above, if you think about it.. if 10 seconds have passed and the computation of velocity in the if statement will yield a huge delta in the next placement of the player.

blissful dagger
#

yup exactly

orchid marsh
#

Which might teleport you through the floor/platform

#

Or in your case, thankfully only jitter.

blissful dagger
#

yea i should take this into consideration if im gonna be making all of these games without unity's built in system

orchid marsh
blissful dagger
#

wait lemme try

orchid marsh
#

Assuming velocity relative to y is some large negative value

blissful dagger
#

im not using any "velocity" its just a value on the y axis since the player is fixed

#

I just add it to diffY?

#

wait that doesnt make any sense

#

velocity is always gonna be +

orchid marsh
#

The idea would be that you'd check for the player's next position rather than the current position - relative to y.

#

As diffy is computed using players current y and platform's position y, you'd simply have to offset by the expected position (including velocity that's going to be occurring this frame) instead of the current position.

blissful dagger
#

ohhh yeah that makes sense

orchid marsh
#

I'm guessing with subtraction if it's a positive value.

blissful dagger
#

yeah ill give it a try wait

orchid marsh
#

Where we're way below the threshold but are still actually near the platform (the distance check, second half of the if statement, will hopefully cover for this).

blissful dagger
#

yeah I think so too but it doesnt seem to work, does adding "padding" to the player help?

#

so like when he gets close

#

it auto snaps?

#

then I can lerp this value with the velocity so I can cover the snapping

#

since nothing else seems to work

#

cuz I suck at these physics stuff lol

orchid marsh
#

Hmm looking back on the if statement, it only occurs if the player is not above the platform. This should instead always be applied because the platform could later set it to zero - if statement is unnecessary here and likewise the bool. Which won't make any difference from what you had before as you've already moved it above the platform check - just tidying up stuff. As for the platform check, formulas should be if the player's position is greater than the platform position plus some threshold offset, set velocity to zero and teleport the player to ground position.

blissful dagger
#

but then when can i add the velocity if i need to control where the player is which is the "break"

#

i thought i needed a bool because i cant set in the loop

orchid marsh
#
velocity = gravity stuff
foreach(...)
    if playerY > platformY + maxNegOffset and playerY + velocity < platformY + maxNegOffset
        position = platform + maxPosOffset
        velocity = 0f
        ...
        break
#

Assuming velocity is a negative number else invert the sign for the second half of the if statement

blissful dagger
#

this makes a lot of sense thank you for explaining!

#

ill see what to modify

orchid marsh
#

With good naming convention substitutes, basically:```
if currentPosY > bottomOfPlatform && nextPosY < bottomOfPlatform
currentPosY = topOfPlatform
velocity = none
...
break

#

(removed numerics and arithmetics)

blissful dagger
#

okayy will do that now

#

Thanks again!

orchid marsh
#

Good luck UnityChanThumbsUp

noble tendon
#

I'm, using unity networkmanager and networkbehavior. how can I assign a specific camera to the player object in the network manager

#

I cant manipulate the camera in the scene through my prefab

#

think i fixed it, it has to be an object not a prefab, if you want to add anything feel free

orchid marsh
violet comet
undone coral
undone coral
merry zenith
#

Hey πŸ‘‹
In the game I'm currently developing I have the need to detect if an event (user input) happened closely enough to a music beat event.
I don't need a full guide, but some direction to follow to investigate how to calculate the time to the nearest beat of the playing audio would be really great.
Thanks!

west scarab
umbral trail
#

Would there be any advantages to putting third party code in local packages? (other than being nicely contained and out of the assets dir) I assume there'd be no difference if they were already in their own assemblies with asmdefs?

narrow marsh
#

Hey guys, in terms of rpg game the account system with database behind saving players credentials and player items etc.
What should i focus on learning? firebase? playfab? photon?

pale silo
narrow marsh
#

Hello guys.

I am searching for libraries to learn about:
-Account creation
-Online gameplay
-Player character information save in a database and not in file (to not being able to edit a file and "hack" the player stats or inventory)

I have searched about it and found some ideias that i would like your opinion about it.
-Firebase
-Photon2
-Playfab

Some basic questions:

  • Firebase does the same as playfab? if yes, which one is the best to learn and use in an RPG game for example.
  • If the game reaches high popularity like "Albion" is there any trouble with max players per room in Photon? or low space on database from firebase or playfab or anyother you guys advise?
narrow marsh
pale silo
#

i have deleted and reinstalled the localization package and i still got the same thing.. the locales aren't being seen

undone coral
#

do you mean realtime multiplayer?

narrow marsh
#

yes

#

albion for example

#

or ark survival

#

or league of legends

undone coral
#

okay

#

what is your goal?

#

@narrow marsh like your goal is to make albion?

narrow marsh
#

that's the game im developing

#

im trying on a blank project to learn about multiplayer stuff on unity engine

#

i want to make dungeons that are able to play with friends

#

and want to make players able to create account in database for example

#

i work using Java and PlSql/T-SQL for 5 years in portugal

#

i program games as hobby eheh
so for example i want to make that game being able to connect to a type of Database where i can use queries(select, updates, deletes...)

undone coral
#

you want to make a realtime multiplayer webgl game?

narrow marsh
#

and also being able to create matchmaking i guess using Photon for what i see atm

undone coral
#

you want to author your own backend*

#

well

narrow marsh
#

for now i export it as webgl game but i will put it at steam

#

for a desktop application

undone coral
#

okay got it

narrow marsh
#

i just set as webgl this beta version because people sometimes don't trust to test games that need to be download ( they might think it have virus and just dont download)

undone coral
#

choosing photon will be the most likely to get you to a working, realtime multiplayer game

narrow marsh
#

I will create a login/register interface before being able to create characters in the account

undone coral
narrow marsh
#

i can use photon for the multiplayer realtime and firebase to save player information?

#

or if i use photon i can't use firebase?

undone coral
#

you can but the scope of technology you will need to learn and master and coordinate between

#

will be more suitable for a team of 4-10 full time engineers

narrow marsh
#

but in the end would be the best choice right?

#

because it would be able to use realtime Multiplayer from Photon and player account/characters/items/equips saved in firebase

#

im right?

undone coral
# narrow marsh im right?

based on the screenshot, it looks like this is a top down persistent world realtime multiplayer rpg, like ultima, right?

narrow marsh
#

i haven't played ultima

#

but yes

undone coral
#

which was made in the 90s and had a budget that's equivalent to like $5 million today

#

so it had none of these technologies

#

so fine, it's like 25 years later

#

i think you can do what you need to do, but firebase and photon work very differently

#

duelyst was built as a hybrid firebase and native backend app

narrow marsh
#

photon isn't all about server host for matchmaking?

undone coral
#

it is a unity multiplayer solutions company for people with budgets

#

its stuff is not vaporware

#

it is also not free. it is also not cheap

narrow marsh
#

but it have a free version to try i guess

undone coral
#

it is cheap in some sense

#

but the kind of technology they make works best for teams of people

#

it makes sense if you have money

dusty wigeon
undone coral
#

unity's gaming service is

#

a copy of photon

#

by transitive property, it is also designed for people with budgets

#

there are few original ideas in multiplayer engineering. if you are trying to make a multiplayer game as a solo developer, you are embarking on a journey through many graveyards

undone coral
narrow marsh
#

yes guys you both make sense about it

dusty wigeon
#

There is not a high number of paradigm possible in Networking. If you say Netcode for GameObjects is a copy of Photon, so Photon is for every other solution that have been develop prior to it.

But I totally agree that doing a multiplayer game as a solo developer is a sucide.

narrow marsh
#

but it is very hard to pick a route of learning at the begining having no one else in the area to walktrough some troubles

#

if u get what i mean...

dusty wigeon
narrow marsh
#

Yes that's a good point ofc

#

you mean like the boss room?

dusty wigeon
#

No, that is a completed project.

narrow marsh
#

what is netcode at all?

#

it enables people to create accounts?

#

or deals with real time gameplay?

dusty wigeon
#

Netcode is equivalent to Photon. It is Unity in house solution that has been recently launch.

narrow marsh
#

Ok so netcode ables me to create a kind of matchmaking right?

narrow marsh
#

FOR EXAMPLE XD

#

sorry caps xD

#

this server dont have any voice chat room?

humble onyx
dusty wigeon
narrow marsh
#

Ok thanks guys ! if you know any discord community that could help me grow in that area i would appreciate to join for sure πŸ˜„
have a good night

misty glade
#

Is there a fixed timeframe for unity versions to hit the LTS track?

I'm going to upgrade my version of unity (9:41pm local, great idea, right?) since we're launching in about 10 days and I wanna hop on an LTS version, but I don't know what to ask to make that decision. I was thinking of 2021.3 but I dunno if I should go with 2022.1 or 2 if they're gonna be LTS soon.

pale silo
#

what causes this error ?

 are trying to be loaded during a domain backup. This is not allowed as it will lead to undefined behaviour!

``` I have nothing, else.. they didn't specify a code line or anything
upbeat path
lapis summit
#

Hello

#

I'm trying to implement A* pathfinding

#

i have a script that calulates a certain objects location and turns the place where the object is on the grid to blue

#

The method returns the correct location

#

but when i run the game The whole grid turns blue

#

instead of just one node

hoary prism
#

Object that's finding path will only be able to move in blue area and anything outside it is unreachable

lapis summit
#

He blue box is the box where the player is ie, the final destination

#

The path itself has a diff implementation

#

But I have brought it down to the code which checks whether the node that the player is on is the node that the code is checking

#

Let me send a ss

#

This is the code

#

The findNodeFromWorldPoint method works beautifully

low notch
#

You literally display all the grid in blue

#
if( n == playerNode)
{
         Gizmos.color = blue;
         Gizmos.DrawCube(....);
}```
#

Inside the foreach ( It's pseudocode )

pale silo
#

Objects are trying to be loaded during a domain backup. This is not allowed as it will lead to undefined behaviour!
I got this error after installing localization package... how do I fix this .. it didn't happen before

lapis summit
#

MB

#

tysm

#

but like could u send it as proper code

#

still cant get it to work

#

result without the playernode implementation

#

result after adding the playernode code

#

(And guess what, the player isnt even on the box)

obsidian glade
#

have you somehow filled your grid with references to the same Node object?

real blaze
#

hey. anyone knows of a trick to load a Scriptable Object at Editor's startup?

#

by load I mean calling it's OnEnable/Awake

#

(without loading it with a predefined path using AssetDatabase)

lapis summit
#

they are different nodes in an array

#

i actually did a check

#

and apparently all nodes are player nodes?

#

or thats what my check told me

obsidian glade
merry zenith
west scarab
tropic stag
#

Maybe someone can help out. I'm working on a mobile game when I want the user to be able to manipulate an object, but it's rendered using a funky displacement shader, so I can't use unity's raycast, because the object is elswhere on the actual screen.
My handway idea is to add another camera, and render that one object to a texture (possibly in a lower rest for performence) and then check that texture with the touch input code. Does that sound correct? is there a simpler way maybe?

lapis summit
#

its merely going thru each node, checking whether that node is walkable or not and whether the player is on that node or not

obsidian glade
#

this code really isn't doing very much, there's limited things it can be

lapis summit
#

Yep

#

but thru debugging it appears that this part of the code is what is causing the problem

misty glade
misty glade
#

I currently use github actions and game.ci's (excellent) github action for publishing my android build directly to google play. We're planning to launch on steam, though, so I need to generate windows builds. On reviewing the documentation for generating windows IL2CPP builds, it seems like there's... quite a bit of complexity and cost. https://game.ci/docs/docker/windows-docker-images

So... I'm going to generate/build these exes on my dev machine and zip/publish those packages to steam directly.

Are there any gotchas I should be aware of with respect to leaking personal information in these builds via Unity?

My current plan was to literally build to a directory (using unity), delete the _DoNotShip folders, zip it and upload it.

candid lodge
#

what is best way to find closest enemy for rogue like game? just thinking about performance.

summer kernel
#

When each enemy spawns, add them to a list. Loop thru the list to find the closest enemy. Or do something simple like overlap sphere or a collider

sly grove
gleaming abyss
#

I am trying to build my project from command line. I am on Windows and I am trying to build a Windows Client and a Linux Dedicated Server build with a single script (the Linux Server build gets containerized later).
Here is my powershell script:

$a = "-quit -batchmode -projectPath ../.. -executeMethod Builder.BuildMain";
Start-Process -NoNewWindow -FilePath $bin -ArgumentList $a```
Here is part of my builder class:
```    static void BuildForPlatform(string[] scenes, BuildTarget target, string platformPath, BuildOptions options = BuildOptions.None)
    {
        BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions();
        buildPlayerOptions.scenes = scenes;
        buildPlayerOptions.locationPathName = $"Build/{platformPath}";
        buildPlayerOptions.target = target;
        buildPlayerOptions.options = options;
        BuildPipeline.BuildPlayer(buildPlayerOptions);
    }```

Is `StandaloneLinux64` the correct build target for building a dedicated linux server? When the powershell script is run, The `Game_Data` and `Game_BurstDebugInformation_DoNotShip` folders are created, but I don't see the executable or `.so` file that normally appears when building from the editor.
gleaming abyss
tired elbow
#

I'm getting a unity editor crash when calling AssetDatabase.AddObjectToAsset on a prefab. This only happens when the prefab is open, otherwise it works fine. Is this a bug?

open drift
#

I’m watching a YouTube tutorial on aoe damage (my concept is a flash baton) in the tutorial he is doing this for a character. So his position is transform.position. Would I need to write something different so that the position it for the object I want it be attached to?

static kelp
#

Does anyone know if it's possible to do something like this

var vertexGraphicsBuffer = mesh.GetVertexBuffer(0);
var sliceOfVertexGraphicsBuffer = ??? //The same vertexGraphicsBuffer, pointing at the same GPU memory, but starting from element of index 10000, and use the next 50000 after that element.

For cases in where the GraphicsBuffer is too big, and I don't really use all that data? Or it'd be pointless to do something like that if the data goes into a ComputeShader, since the data is already in the GPU?

sage radish
midnight violet
daring pelican
#

Hey guys, is there a way to get these values from the project settings via script? OR, alternatively, get these values from the dashboard??

midnight violet
daring pelican
daring pelican
#

Facepalming so hard

midnight violet
#

Yeah, just know what to google for πŸ˜‰ Its in playersettings, that has its own implementatino to be used in code πŸ™‚

daring pelican
midnight violet
daring pelican
tacit coyote
#

btw is there a good guide/any common advice for using git with Unity? getting to the point in my project where i really ought to start using version control and i dont wanna fall into any well known pitfalls

midnight violet
daring pelican
# midnight violet You are welcome πŸ™‚

Hey so the signature for this message is GetPlatformGameId(string platformName); but any ideas what to use with platformName? There's, like, no info on this anywhere... I tried using "Android", "RuntimePlatform.IPhonePlayer", etc. But it just returns an empty string...

midnight violet
scenic forge
#

If it’s stored in PlayerSettings, you can open that file and see what’s used there, decent chance that will be it.

daring pelican
scenic forge
#

At worst you can use reflection/parse the file manually.

midnight violet
daring pelican
daring pelican
#

thanks again

#

OK it seems I need to go get some rest lol

#

So AdvertisementSettings.GetGameId(RuntimePlatform.IPhonePlayer) works as intended

#

Why do we need AdvertisementSettings.GetPlatformGameId("RuntimePlatform.IPhonePlayer") ? Returns an empty string

midnight violet
daring pelican
#

Thanks for the help, guys!

crystal parrot
#

is building dedicated server broken for ECS?

NullReferenceException: Object reference not set to an instance of an object
Unity.Scenes.Editor.EntitySceneBuildPlayerProcessor.HandleGetBuild (UnityEditor.BuildPlayerOptions opts) (at ./Library/PackageCache/com.unity.entities@1.0.0-pre.15/Unity.Scenes.Editor/EntitySceneBuildPlayerProcessor.cs:71)

lament trout
#

Hello does anyone have a good resource so I can learn to code with C#. I have an idea of being able to move things in unity on a shelf and count the amount of liquid in the bottle i.e. a full bottle counts as 1.0, if the bottle is 75% full then it would say .75 or if it is 34% full then it would say .34. Then I would like to send all that information to an excel spreadsheet. Can anyone point me the right way to learn this skill?

daring pelican
# lament trout Hello does anyone have a good resource so I can learn to code with C#. I have a...

Exporting data in Unity to open in Excel as a spreadsheet - writing using CSV format, Super Easy!

Follow me on twitter https://twitter.com/JamesDestined
Follow me on instagram https://www.instagram.com/artbydestined/
Buy my pieces on redbubble http://DestinedArt.redbubble.com

Any comments or questions welcome. Enjoy the video!

Song: TheFatRat...

β–Ά Play video
gleaming abyss
#

Anyone know what the default script build settings are when building with BuildPlayerOptions? My Windows Client build works from the editor, but I get a crash when running the build created using BuildPlayerOptions. The crash occurs at a block of code in a #if UNITY_SERVER define block, but I didn't define that anywhere in the BuildPlayerOptions (and I don't want it defined for my client build). Additionally, the BuildTarget is StandaloneWindows64 and the StandaloneBuildSubtarget is Player

gleaming abyss
#

Seems to be that somehow some of the build settings are carrying over when I have a single function create multiple builds...not sure why that is the case but when I only build one at a time they all work properly.

midnight violet
pale silo
#

if anyone can help please, I am trying to open up a webgl app but when I use a long link I get this error in the browser:

**Forbidden**
You don't have permission to access this resource

I need the URL to be that long

sly grove
midnight violet
pale silo
sly grove
pale silo
sly grove
#

it's not about the length

pale silo
midnight violet
open drift
#

I’m making a flash baton. How do I give it a trigger kinda like a gun that the player presses and it causes damage

midnight violet
#

I guess you are just trying to access a link that returns a value you are not allowed to checkout with the default public user the webgl represents

open drift
#

Whats the issue @sly grove

pale silo
midnight violet
midnight violet
sly grove
#

three channels actually

pale silo
sly grove
modest vale
#

DataArray Structure

karmic viper
#

question

icy smelt
#

When using the MeshData API, I'm getting: Skinned mesh attributes use wrong streams
This error does not happen on Unity 2019.4.40f1, only on newer Unity versions.
What the defines the right streams to pass on the vertex attribute layouts?

timber flame
#

Which one do you prefer?
For example inside an event listner, you get a base instance, for example a building has been added.
Now, inside the listener, you want to do some stuff if that building has type ConcreteBuilding

// is operator
public void OnBuildingAdded(Building building){
    if(building is ConcreteBuilding){}
}

or

public void OnBuildingAdded(Building building){
    // building type enum 
    if(building.Type == BuildingType.ConcreteBuilding){}
}

or completely different way, for example keeping buildings based on type and raise events

midnight violet
#

With the enum you can also just fill it in from a database or or or, with the class approach, you will always have to touch the source to add new types

tawny bear
#

Yeah I'd go for the enum approach as well

analog nexus
#

is anyone using custom roslyn analyzers? I can see it working, it is creating the warn ing I expect. however unity complains about it miossing references

#

I'd like to get rid of the error as to not confuse the team

#
Reference has errors 'Microsoft.CodeAnalysis'.```
#

so it seems like the analyzer is being loaded into a different process or appdomain where the reference does work but then unity tries to load it as a unity plugin regardless?

#

ooh

#

better read closely:

#
Step 2 : Import the .dll files to Unity

2.1. Copy your analyzer's .dll files into your Assets folder (or any subfolder)
2.2. Select them in the Project windows in Unity and open them in the inspector
2.3. Under "Select platforms for plugin", disable everything like this :
#

disable all platform to not include it in the app build

icy smelt
#

Could someone explain me what this means?

#

This means I need 3 different structures to hold my vertex data so I can pass each one of the structures to the output stream?

#

So I should split my data in 3 different structs to pass to the SetVertexBufferData? (In the context where I use all vertex attributes)

sage radish
icy smelt
#

All my data is inside a single struct, generally, so there are lot of changes I have to do

#

Been using a single stream to handle all the data, but newer Unity versions are messing up my mesh data, so I guess I need to pass the data on different streams as it wants, idk

short fog
#

hi, i have a player controller script, when player touches the ball; ball position is setting to players forward position.

but i dont have a dribble system. When i run/walk, ball doesnt move and its awful.

how can i make a dribble system like this? "https://youtu.be/-47ak3wYHZs?t=510"

⚠️: if ball is far from player, player shouldnt move

HEDΔ°YEEEE STEAM OYUNUUUUUUUUUU!!!:D
Oyunu alan arkadaş yorum kısmına oyunu aldığına dair mesaj atarsa sevinirim.

Sanctum: Collection
https://www.humblebundle.com/?key=RuVFke3dKAyZmF3m

β–Ά Play video
keen cloud
#

how would I do something like this for unit testing a monobehaviour? It's UI so I would like to just check if the text boxes were set properly

shy violet
#

does anyone know any good online leaderboard/server storage API's?

#

for unity

#

that are free bc im broke πŸ˜₯

#

i tried loot locker but stopped using it bc its not what I am looking for
Idk how to get certain users so i can display a high score πŸ’€

The current solution works but its terrible

#

its this very old leaderboard API from the 90s πŸ’€

jolly token
#

Add the TextMeshPro reference to the test asmdef

short fog
#

how did he do this πŸ’€

sage radish
shy violet
#

SO on a website or unity's show case site

austere roost
#

Can scriptable object sub assets also have sub assets? (essentially making a folder-like structure) or is it just 1 level? Because it's giving me this weird error : AddAssetToSameFile failed because the other asset is not persistent

keen cloud
#

unless something else needs to be done

jolly token
#

Does your test assembly references your main assembly?

#

Also you probably wanna do new GameObject().AddComponent<MyComponent>() not new MyComponent()

keen cloud
keen cloud
jolly token
#

Not the test one?

humble leaf
#

@short fog Stop crossposting

short fog
keen cloud
#

this is my main one

short fog
#

beginner couldnt help me, general couldnt help me...

jolly token
tacit pasture
#

hi

jolly token
#

You won't want nunit in your build

tacit pasture
#

@short fog bro i love you. You are pro you coding a best game.

humble leaf
# short fog beginner couldnt help me, general couldnt help me...

You ask in one channel, and you stay in one channel. That's how this discord works. Asking how to make a "dribble" system is too large a question. Lots of people here are capable of eventually creating something like that, but nobody here is going to hold your hand in doing so. It involves a lot of work.

keen cloud
tacit pasture
keen cloud
#

also apologies im just in class and am not focused 100% on your help may i come back later? i feel bad lmao

jolly token
short fog
keen cloud
#

thank you

jolly token
#

No problem

tacit pasture
humble leaf
tacit pasture
#

i am metin2

humble leaf
#

!mute 645975394369011712 3d You can come back and try again. Or leave, it's up to you.

thorn flintBOT
#

dynoSuccess Hamitttt#9623 was muted

violet iron
#

Is there a way to tell from a renderer if the material it has assigned to it is an asset reference or an instance that only exists in runtime and hasn't been instanced apart of the asset yet?

fresh salmon
#

Learned that a few days ago: if you call .GetInstanceID() on it and it returns a positive number, asset reference, negative number, instance of an asset

violet iron
#

just to be safe, 0 is considered positive in this context. correct?

#

so id>=0 is an asset ref?

fresh salmon
#

Docs don't mention it, but I would say it cannot be 0 ever

violet iron
#

thing is i've seen 0's before, but i think it may have been for null entries, so that's probably fine

#

(came up in serialized structures, not in explicit id fetchings)

fresh salmon
#

Oh recent docs says it's never zero, was on an old page

dusk plaza
#

Can anyone help me with calling DLL functions in Unity?
I have this DLL that I don't have the source for, and using DLL Export Viewer I can see it's functions, but how do I call them?

This DLL functions show significantly differently from the functions from the other DLL I have whose functions I already call:
For the second image, all I need to do is:
[DllImport("DLLPATH")] public static extern int getCameraWidth();
and I can easily call the function. But I can barely understand what each line in the first image mean, besides that those are functions on the DLL

chrome dragon
#

I want to create a premade script when clicking an option, sort of like how I can create a new scene when clicking "Scene", but It'd be my own name with my own script. Thanks in advance!

keen cloud
# jolly token No problem

Alright so I added Unity.TextMeshPro to the asmdef and used "EditJobDatabaseMonoBehaviour edit = new GameObject().AddComponent<EditJobDatabaseMonoBehaviour>();" instead of the usual way of creating an object but it is saying that the "Object reference not set to an instance of an object" still

#

it's saying the error line is here where i set the code.text

#

when i print the same line above it is not null

timber flame
jolly token
timber flame
#
public void OnBuildingAdded(Building building){
    building.HandleIfAdded();
}

Probably, this approach is better. I do not like casting or is check as well as type checking by enum

midnight violet
#

As said, it depends on your setup.

keen cloud
#

but when I set it it gives the error

#

like when I set code.text to jobdata.read

tropic stag
#

I have some UI and a "safe area" script, resizing a panel to make room for the notch, and my ui elements are positioned relative to it. Everything was working fine, until I added tweening with Dotween. I'm animating the ui elements with DoScale and DoLocalMove, and after a change in orientation they fly of the canvas. Does that make sense to anyone? If I'm animating and reseting local position this should all work relative to my safearea anchors, anyone ran into a similar problem?

#

(also now that I'm trying to debug this, my stored reference position (objText.gameObject.GetComponent<RectTransform>().localPosition) doesn't match the inspector, it looks like absolute coords relative to the canvas origin?)

#

ok, sorry for rubberducking this problem here, but apparently dotween has a DOAnchorPos for animating UI elements!

wild ocean
#

I'm wondering about good ways to store data for my strategy game. Currently I'm doing it with multi-dimensional variables, for example all of the game's troops are stored in a public static variable:
Dictionary<int, List<int>> Troops; where the key is the position of the troop and the list of integers is a list of attributes. So Troops[100][3] would be the health of a troop located at position 100. However this is a pretty flawed and unintuitive approach, for obvious reasons: you have to remember what attribute each index has, and it can only store integers.

I'm considering making a Troop class, so i can instead have it in a List<Troop> object to fix these issues. However I'm wondering if there's a better approach, or if I should be using variables at all. (I've heard of scriptable objects but I'm not sure what those are). If this is relevant, I'm planning on making the game be multiplayer, so this data would be synced across players.

sly grove
#

where Troop is a class containing information about whatever unit is at that location

#

or sorry, if your positions are just int then Dictionary<int, Troop> or List<Troop> is enough

wild ocean
#

yeah, i said i was thinking of using List<Troop> (i'll probably put the information of the position in the Troop object, and have some sort of Troop getTroopAtPosition(int position) function in the troop class) i wont do that, instead ill have a Map object that has a copy of the reference to the troop.

sly grove
#

Troop getTroopAtPosition(int position) doesn't seem like something that would go in the Troop class

#

rather some kind of GameManager or BoardManager or something

wild ocean
#

alr

#

what about scriptable objects?

sly grove
#

what about em

wild ocean
#

how do they compare to classes and regular objects?

sly grove
#

ScriptableObject is a class

#

not sure I understand the question

#

ScriptableObjects are objects that you can create instances of as assets in your project

#

not sure how it's directly applicable to what you're asking

wild ocean
#

oh but theyre otherwise the same thing?

sly grove
#

they're not the same thing

#

in any sense

#

I don't really understand what you mean by that

wild ocean
#

well an object is an instance of a class, so is a scriptableobject also an instance of a class?

sly grove
#

No ScriptableObject is a class

#

an object that is an instance of a class that derives from ScriptableObject is an instance of that particular class, and an instance of ScriptableObject.

wild ocean
#

alright, thanks

jolly token
keen cloud
round summit
#

Greetings! I'm having issues with a dictionary in which I'm adding gameobjects as the key. I added the gameobjects to the dictionary using an object pooling system in which it already had its own dictionary. But when I search for the game objects in the dictionary it says the key isn't found despite the gameobjects clearly being in the scene. Does anyone have experience with this?

brisk pasture
#

is this at runtime or editor

round summit
#

Runtime

brisk pasture
#

dictionary is not serialized so will not save in the inspector

gleaming abyss
#

Is there a trick to getting scripting defines working consistently? I have a define block in my code, and the exact value is in the scripting define variables, and the code isn't running

brisk pasture
#

@round summit how are you setting the keys for the dictionary

#

like GameObject is pass by reference so would need to be the exact same one to be a valid key

round summit
#

So here I add the items to the pool using the game object as the value and name as the string

#

But then this is where the actual characters create their friendlist using the same pooled gameobjects

#

But using the values as the keys in this new dictionary

#

Oh shoot, you know what?
I'm not adding them from the first dictionary I'm adding them from an array

#

One sec

#

I'm testing this for right now

#

Yeah! That seemed to do the trick

brisk pasture
#

rubber duck

round summit
#

Rubber duck indeed πŸ˜‚

bold vine
#

I'm trying to create my first plugin for iOS but I keep getting these same errors
Undefined symbol: _createPaymentRequest and Undefined symbol: _showPaymentSheet

Neither of my methods are defined with the leading _
This is in my .h

#ifdef __cplusplus
extern "C" {
#endif

void createPaymentRequest(NSArray<PKPaymentSummaryItem *> *items, NSDecimalNumber *total);
void showPaymentSheet();

#ifdef __cplusplus
}
#endif

and in my C#
[DllImport ("__Internal")]
private static extern void createPaymentRequest (string items, string total);

[DllImport ("__Internal")]
private static extern void showPaymentSheet ();
#

I can't figure out what I could be doing wrong

long ivy
#

"__Internal", createPaymentRequest parameters are wrong

bold vine
#

Okay, I see that error

#

But the showPaymentSheet doesn't take any params

long ivy
#

that's why when you compile it after fixing the imports, it's going to say it can't find createPaymentRequest instead of not finding either of them

bold vine
#

I'll give it a shot

bold vine
#

Are there any good plugins that implement Apple Pay?

glad oracle
#

How do I print a value to the log? It’s been a while for me.

glad oracle
#

Oh thanks I forgot

#

It’s been a while

mental hound
#

I need a bit of help with triggering the Resources.UnloadUnusetAssets() properly, for some reason, this method of Resources will only trigger when a new frame has been generated, here is a snippet of my code (https://paste.mod.gg/bzdsicquyxbu/0).

What happens is that I load a bunch of sprites in memory using Resources.LoadAll<Sprite>("path") for a specific list, then when I want to unload the sprites to free up memory, it does nothing and goes to the next LoadSprites method, filling up the memory up to 7GB of RAM before cleaning up the unuset assets, does anyone have an idea how to solve this?

mental hound
#

For some reason, this doesn't have so much of an impact in the build version (it just uses 200 MB of RAM then finished loading and unloading), but in the Unity Editor this can amass to a few GB (way above the size of all the files).

crude isle
#

Is it a bad idea to have a struct type contain mutable reference types? I have an EventBus type class (based on a git repo I found a long time ago) that uses structs as both event "ID's" and also as the container for the events arguments/data/whatever. When a new event is raised i'm passing in a new struct of the event type and sometimes passing GameObject or script references in that structs constructor. I could probably switch to classes and just use pooling but I like the struct setup...

#

Here is the event bus class

#

Here is an example of an event Struct...

near arch
sage radish
fair hound
#

if I have a serialized Object which stores references to joints + the objects they connect, and I have a hierarchy of classes which need the joint type to vary, what would be a good way to communicate joint types between the serialized object and the derived class without needing a ton of extra references?

brisk pasture
#

store a struct that contains the reference and a enum representing the joint type

fair hound
#

Im not very familiar with structs but wouldnt this still cause an issue if the treatment of certain joints isnt type specific? I want to be able to have two of the same type of joint and two different, but assign different behaviours per joint.

sly grove
fair hound
#

Yes, I need to be able to access derivative type fields.

brisk pasture
#

ah

#

you might have to Store as Joint then later use pattern matching to figure out what kinda joint it is

#
switch (joint) {
    case CharacterJoint characterJoint:
        break;
    case ConfigurableJoint configurableJoint:
        break;
    case FixedJoint fixedJoint:
        break;
    case HingeJoint hingeJoint1:
        break;
    case SpringJoint springJoint:
        break;
    default:
        throw new ArgumentOutOfRangeException(nameof(joint));
}
#

for example

fair hound
#

that could work, thanks!

bold vine
#

Has anyone successfully created a plugin for Apple Pay? Not for IAP, since we're working with physical products.

karmic surge
#

this seems to be silly, but if I want a unity program to communicate with another program, how do I do it?
(the other program ill send frames, and unity code will do some pre-processing effect to those frames)
any ideas? I looked into this:
https://learn.microsoft.com/en-us/windows/win32/ipc/interprocess-communications?redirectedfrom=MSDN
but I was hoping for something ready-to-use builtin

rough sky
#

I have written a custom HDRP post process, but it is not rendering nor is it printing any of the debug lines, am I doing something drastically wrong? ```cs
using System.Collections;
using UnityEngine;
using UnityEngine.Rendering.PostProcessing;
using UnityEngine.Rendering.HighDefinition;
using System;
using UnityEngine.Rendering;

[Serializable]
[VolumeComponentMenu("Transition/SubtractiveFade")]
public sealed class SubtractiveFadePostprocess : CustomPostProcessVolumeComponent, IPostProcessComponent
{

Material m_Material;
public ClampedFloatParameter completion = new ClampedFloatParameter(0, 0, 1);
public bool IsActive() => m_Material != null;

public override CustomPostProcessInjectionPoint injectionPoint => CustomPostProcessInjectionPoint.AfterPostProcess;

public override void Setup()

{
    Debug.Log("Starting");
    if (Shader.Find("Custom/SubtractiveFade") != null)

        m_Material = new Material(Shader.Find("Custom/SubtractiveFade"));

}

public override void Render(CommandBuffer cmd, HDCamera camera, RTHandle source, RTHandle destination)
{
    Debug.Log("Trying");
    if (m_Material == null)
        return;
    Debug.Log("Got it");
    m_Material.SetFloat("_Completion", completion.value);

    HDUtils.DrawFullScreen(cmd, m_Material, destination);
}

}

#

All it is, is a material is created from the shader, then it is blitted to the screen in Render()

#

But nothing happens - I'd assume it's a non-existent shader path, but it is also not running the print commands

shadow shore
#

I have a server backend using Auth0's openid-connect and I want to detect who I'm logged in as inside my Unity game - how do I do this?

#

speficially OpenID, NOT oauth2 (although if its easy to change this then maybe i can use OA2)

#

I want my unity app to be able to read the token essentially, and then use it to access protected endpoints.

sly grove
#

Unity shouldn't be doing that

#

it should be sending requests with the token

#

the server uses that token to check if the request has access to a given resource

shadow shore
#

do I send them over a websocket once I'm done logging in on the "backend"? i was thinking about doing that but realised it might not be the generallyaccepted method

shadow shore
#

currently only the web browser can see the token

shadow shore
#

user logs in on website -> the website now knows the auth0 token -> get this back to unity securely(???) -> unity can now use this information to access endpoints -> profit

sly grove
#

Is that what you're saying?

#

and you want to communicate the token to the Unity app running in the page?

shadow shore
#

all of the login stuff is currently done on the JS side yes

shadow shore
#

but I imagine it would be p much the same with webgl vs mobile native

sly grove
shadow shore
#

nope

sly grove
shadow shore
#

maybe I could convert it to webGL somehow, im using an AR project

#

or at least will be implementing the AR stuff later down the road

shadow shore
#

am I actually able to export an AR app to unity WebGL?

#

it uses ARCore and stuff

sly grove
sly grove
#

never used AR

shadow shore
sly grove
#

Nothing leaves your computer

shadow shore
#

how can it listen without port forwarding

shadow shore
sly grove
#

I'm confused about where this all is running.

shadow shore
#

its written in nodejs it cant run on the user's phone

sly grove
#

you said there's a JS part

#

OK NODEJS

shadow shore
#

yep

sly grove
#

I thought a web browser

#

on a desktop pc

shadow shore
#

ohhh no sorry the backend is node

sly grove
#

maybe explain what this setup is lol

#

Because I'm lost

sly grove
shadow shore
#

backend in node, unity app that will run on a phone

shadow shore
sly grove
#

ok so there's no Javascript. Unity is making requests directly to/from the nodejs server

shadow shore
#

yes

sly grove
#

Ok so I'm confused what the question is exactly

sly grove
#

what website is that

shadow shore
#

how do I get the token from the backend into unity, and secondly, how do I then use that token to access the endpoints

shadow shore
sly grove
#

So is this a process where the phone's web browser opens

#

to do the login

shadow shore
#

yes

#

well thats what I hope to do, atm im testing it on PC

#

either way a web browser opens to perform the login

sly grove
#

Ok, Pretty sure the way that usually works is Unity will have sent some request to the server first and gotten some kind of token back

#

and then once the login in the browser is complete, you send another request with that token and the server gives you the valid auth token back

#

and now you can make normal, authorized api requests with that

#

Either that or the auth request remains open while the user is logging in

#

and returns finally when it's done

shadow shore
#

that seems quite complicated icl, I'm not sure how i would implement this in code

sly grove
sly grove
#

in between those two the login happens unbenownst to your Unity code

#

1 and 3 are the request and the response

shadow shore
#

by send an auth request do you mean opening the browser to let the user login?

sly grove
#

no

#

ah right how does the browser open then

shadow shore
#

one sec gonna get a drink and i'll come back to this

#

lemme make my repo public and i can show you what the backend is doing

#

this is the backend code

#

god i hope there's no token leaking going on here /hj

#

auth0 docs page is down 😦

#

the docs being down does NOT help matters

shadow shore
#

I have no idea how to connect this api thing to my actual running backend

warm stump
shadow shore
#

the docs pages are still down

shadow shore
#

again the docs being offline (500) for me is super annoying

warm stump
#

There's no "one" way. I guess it just depends on your requirements.

warm stump
shadow shore
#

I'm new to all this auth stuff

#

if you know how I should fix it i would greatly appreciate any form of JS or pseudocode ive been stuck on this issue for like two whole days

warm stump
#

What ide are you using, there are commands that create express app boilerplate code. You are missing a ton of stuff like setting up your views directory and template engine etc. You are also using a typescript file but not programming in "typescript"

shadow shore
#

VSCode

#

I'm not making a website here, just a simple backend

#

I want the user to login and then for the browser to close and send the login info to another app (in this case unity)

#

I'm only using the browser as a login screen basically

warm stump
shadow shore
#

I want the game to open up a web window, the user logs in, the game then has their login info. The game and the web backend are entirely separate

#

less of a game more of an app, but made in unity

#

I know there's some unity specific stuff for google play but I want users to be able to login with multiple services

warm stump
#

So you should be creating the UI for the login system within your game. Making a Post request to your backend with their credentials and verifying them. When they are verified, you send back a token to them and store it with an expiry time. In your backend you would create a collection that stores login timestamp with their generated token along with an expiry time. This is assuming you are creating it all from scratch yourself and not utilizing 3rd party login systems.

shadow shore
#

creating the UI in unity was a major thing i was trying to avoid doing hence the web stuff

#

I'm using auth0 not creating anything from scratch

#

I wanted specifically not to make UI in unity for logging in, unless i can have a webview inside unity that I'm able to extract data from maybe?

#

are the docs downfor anyone else?

shadow seal
#

Just you

shadow shore
#

damn

#

I cant check any tutorials or anything

#

I need to get this working its an important part of the project

#

fixed it, relogged

#

I've asked about implementing this stuff on their forums, lets hope its active over there

shadow shore
shadow shore
#

yall get that feeling where every link on google is purple and you still have no answer?

coral citrus
#

is anyone familiar with using rendertextures to draw meshes?


        public IEnumerator RenderFace() {
            WaitForEndOfFrame frameEnd = new WaitForEndOfFrame();
            Player p = GetComponent<Player>();
            RenderTexture.active = faceTexture;
            Graphics.DrawMesh(p.baseSouth.GetComponent<MeshFilter>().mesh, Vector3.zero, Quaternion.identity, p.baseSouth.GetComponent<MeshRenderer>().materials[0], 0);
            yield return frameEnd;
            Texture2D tex = new Texture2D(faceTexture.width, faceTexture.height, TextureFormat.RGB24, false);
            tex.ReadPixels(new Rect(0, 0, faceTexture.width, faceTexture.height), 0, 0);
            tex.Apply();
            Sprite newSprite = Sprite.Create(tex, new Rect(0, 0, faceTexture.width, faceTexture.height), new Vector2(0.5f, 0.5f));
            demoSprite.sprite = newSprite;
            RenderTexture.active = null;
        }
#

i've had absolutely no luck with this in any form

#

i can't get anything to draw on the rendertexture in question

dusty wigeon
coral citrus
#

i was trying to draw an existing rendered mesh onto a rendertexture, but wasn't having much success

#

the only way i've been able to get it to work is using a camera yeah

#

but it seems like the alternative would be more efficient, if i didn't need to use a whole separate camera for it

dusty wigeon
#

because it is how you should do it.

#

How can you render a mesh, without a camera ?

#

You need the projectmatrix, viewmatrix, etc. that camera provide. The camera is not heavy, it is pretty much just that.

stark crag
#

I have an issue, wondering if you could help me.

I have a top-down (it is actually 3d game, but the controls are only in the x,z plane) space type game, so you are controlling your ship with tank controls. The movement is controlled by the physics on the ships rigid body, while I am performing rotation directly (to avoid spinning the ship which is physically accurate but hard to control). I can rotate the ship clockwise, or counter clockwise fine. If the user presses back (S) I want the ship to rotate to the opposite of the vector of movement (rigidBody.velocity.normalized * -1). The ship has a turn speed, so I want it to rotate towards the new position, while obeying it's turn speed.

I don't know how to tell the object to rotate towards a new vector partially. Right now the turn speed is represented as 192, and it rotates 192 * time.deltaTime each frame.

undone coral
shadow shore
#

im doing this for a mobile app and dont wanna buy anything

#

Authentication lets you control access to web application routes and API endpoints -- it's not just about knowing who's logged in. This video expands on previous episodes, taking our authenticated Node.js/Express web application, adding pages that can only be accessed when logged in, and creating a secured API that's called from the web app.

If...

β–Ά Play video
#

i need to separate my "webapp" and my "apI"

undone coral
stark crag
#

@shadow shore If you control both the login site and the mobile app, can't you expose a Rest API and just make your own login UI instead of showing a webpage?

shadow shore
undone coral
shadow shore
#

i think i've come up with a system but its a little jank

#

what im doing now is this:

- server stores session with ip hash for lookup
- after login the server checks for that session key
- once it finds the session key it stores it alongside login token in cache
- unity can then use the session key to lookup the token```
#

the problem with this is i just found out that i cant get an API access token from just logging in as a user

undone coral
#

okay

shadow shore
#

thats for something different

#

i want to get an api token so unity can access the secure endpoints

#

req.oidc.accessToken is undefined when logged in as a user

undone coral
shadow shore
#

well the obstacle is ive been trying this for 2 whole days and havent managed

#

its difficult and im new

undone coral
#

okay

shadow shore
#

why not

undone coral
#

it sounds like you want the profile information

shadow shore
#

yes, inside unity

#

and also an auth token so i can access secure endpoints, in this case making social media-type posts

undone coral
#

i get it

#

so listen

#

have you been able to login yet or no

#

do you have that working?

shadow shore
#

yes

undone coral
#

are you sure?

shadow shore
#

what do you mean by this

undone coral
#

if you are logged in, you have 3 tokens

  • an id token
  • an access token
  • a refresh token
shadow shore
undone coral
#

they are labeled as such in the callback reply you get from your OWN implementation of an oidc login. you will need your OWN backend to process this

#

do you have the 3 tokens?

shadow shore
#

I'm not sure, I can access the id token

undone coral
#

lol

shadow shore
#

is the refresh part of req.oidc

undone coral
#

access the id token is just funny sounding

shadow shore
#

i literally followed that tutorial

#

i can retrieve it then lol

#

but idek what a refresh token is

undone coral
#

okay well

#

your application type is obviously native

shadow shore
#

why cant I just get the accesstoken when logged in as a user? thats what im wanting to give back to unity

undone coral
#

and hence this tutorial is not helpful to you

shadow shore
undone coral
#

i think you are doing something pretty complex

#

without using an appropriate asset

#

which will help you a lot

shadow shore
#

is the asset free and does it work on mobile

undone coral
#

i don't know. you should look for one

shadow shore
#

i did

undone coral
#

i believe auth0 has a unity package

shadow shore
#

there isn't one for this afaik

#

for VR projects

undone coral
#

it doesn't erally make sense to login while wearing a headset

shadow shore
#

and it uses an entirely different system

undone coral
#

is this a quest?

shadow shore
#

yep

#

im just wanting to make a mobile app

undone coral
#

huh?

#

what is the game?

#

what is this?

#

you said "just" and "mobile app" but also "vr"

#

you have a website now, where you can login with auth0

#

and this gives you a token, but i don't see how this advances your goal of having an oidc id token, access token and refresh token inside your vr game

shadow shore
#

i dont have a vr game

#

i was talking about that assrt

undone coral
#

i see

shadow shore
#

its just a normal unity app

#

i want the app to pop open a browser, user logs in, the game retrieves that login data (access token for api)

undone coral
#

okay

#

i think you should use playfab for user accounts

shadow shore
#

how is this so difficult, what am i doing wrong, and also is there anyone who can help me write this code because i have been at my pc for like 14 hours now

shadow shore
#

i want users to be able to login with existing socials and not username/password btw just in case playfab doesnt have that

#

hmmmm

#

this might be what i need... but how can I auth on the backend with this?

#

ok cant find anything on making a backend in nodejs

#

hmmmm

#

maybe this is how i can implement it still using auth0

shadow shore
#

alright, this seems to work just how I want it to

#

I need to make some basic UI but it still works great

humble charm
#

can you call a method when list.Add is called?

midnight violet
humble charm
midnight violet
humble charm
midnight violet
humble charm
midnight violet
tawny bear
#

(@humble charm)

#

You could even overload the same method probably

midnight violet
tawny bear
#

Let me try

midnight violet
#

Like with an extension you would need to pass in the delegate or rather the action/event to callback, right?

tawny bear
#

Because I first thought it was just do an additional thing upon adding

midnight violet
#

Yeah he wants to call a delegate when a List is being modified I guess

tawny bear
#

But if he specifically wants an event bound to that specific list then a custom class might be needed yeah

tawny bear
midnight violet
tawny bear
#

It's also kind of the question how much he will use it, because if it's like one time, then why not run an event right after or before the addition?

#

Instead of making a whole way around it

tawny bear
# midnight violet I guess bound to that list. But well, only he/she knows πŸ˜„
using System;
using System.Collections.Generic;
using UnityEngine;
using ExtensionS;

namespace ExtensionS
{
    public class ListEventHolder
    {
        public Action onAdd;
    }

    public static class ExtensionMethods
    {
        public static void CreateListEvent<T>(this List<T> list, out Action listEvent) 
        {
            ListEventHolder listEventHolder = new();
            listEvent = listEventHolder.onAdd; 
        }

        public static void Add<T>(this List<T> list, T add, Action listEvent)
        {
            list.Add(add);
            listEvent?.Invoke();
        }
    }

}
public class Test : MonoBehaviour
{
    List<int> list = new();
    Action listEvent;

    private void OnEnable()
    {
        list.CreateListEvent(out listEvent);
        listEvent += () => print("Test");
    }

    private void Start()
    {
        list.Add(1, listEvent);
    }
}
#

This would work

#

Though at this point it's probably better to just use your own class

tawny bear
#

(Also the namespace is ExtensionS because I already have on that is called Extensions heh)

#

Also if he just wants to have an delegate be called along with adding something then doing

     public static void Add<T>(this List<T> list, T add, Action onAdd)
        {
            list.Add(add);
            onAdd?.Invoke();
        }

Is all you've to do

#

You could expand that to check to only have it run the event if it's successfully added

#

Though that'd be more of a thing you'd do for a hashset probably

#

Anyway you can slap this on an object in scene and it should work.
(Note that in the end the classes should be seperated, but to test it, it works fine)

#

@midnight violet What do you think of this approach by the way?

midnight violet
tawny bear
#

That reminds me, I should probably have lunch as well so ima do that now πŸ˜…

dusty wigeon
tawny bear
dusty wigeon
#

Yeah, srry was just trying to figure out what you were doing. It doesnt seem well executed.

tawny bear
#

It depends on the context if you’d want it or not

tawny bear
dusty wigeon
#

You want to trigger an event when an object is added in a list ?

tawny bear
#

But he wasn’t very descriptive so I just was making some random code

tawny bear
#

At least that is what we think he wants

dusty wigeon
#

Then you should create a wrapper around the list that expose all the list functionality. You could also maybe inherit from it, depends on how the list has been made.

tawny bear
#

That’s why I suggested a custom class for lists with events is probably better

dusty wigeon
#

The event shoud be inside the list.

#

Definitly better

tawny bear
#

Yeah, but I just wanted to do it with extension methods just to see, it really depended on the context of what he exactly wanted, if it’s for this case then using a custom class would be better, if it’s for the other case an extensionmethod would be better

dusty wigeon
#

In the given scenario, it is maybe true that it could work. But if you extrapolate this in the future, you might find your self cripple.

tawny bear
#

Yeah as I said before, it really depends on the context

#

Which we weren’t given a whole lot of

dusty wigeon
#

I mean, whatever the context, the pattern you are expressing is hardly maintainable. (I'm not trying to insult you, I'm just giving insight and criticism)

tawny bear
#

Oh yeah no I’m aware that it isn’t a good solution

#

It was just interesting to see in what way you could do it with Extension Methods

#

It’s also annoying to use since you’ve to keep passing the action back into the addition to use it

tawny bear
dusty wigeon
#

Extension method is not used to override a behaviour, but to add one. In those contexts, composition or inheritance are more adapted to solve our issue
But let's we really need to have an extension method.

I would use a Pub/Sub + Singleton instead of passing back and forth the event.

{
    list.Add(add);
    Channel.Instance.Publish(Event.Add, this);
}```
midnight violet
#

That would result in calling the function here when add something, quite nice, even if the inspector is not showing the List right now πŸ˜„

public class ListTester : MonoBehaviour
{
    public System.Action testAction;
    public CustomList<GameObject> test;

    private void Start()
    {
        test = new CustomList<GameObject>(()=>{ Debug.Log("Custom Event from List Add");  });

        test.Add(gameObject);
    }
}
#

You mean like

#

#if UNTIY_EDITOR and stuff?

#

Oh you mean for the system like JAVA_HOME etc?

dusty wigeon
#

Otherwise you create a wrapper

midnight violet
#

the problem is that on OSX env vars in terminal set are not present for apps called from finder/spotlight, if I got you right with the env vars πŸ˜„

#

Seems to be what you want

#

uhh, well that is quite nice to know, thanks for asking πŸ˜„

#

Not yet sadly. My projects were either to simple to really needed to be tested (exhibition installations and standard AR stuff) or too abstract to be tested πŸ˜„ But if you ever got somethign to share, I am very interested in that field too, just had no time to dig in to it

#

as you said, it depends on what you are testing. Are you testing forexample tower defense waves and try to balance them, tests make sense. Also for performance testing or as you said, prefab handling and so on. But it depends on the size of your project, the team, the outcome you think you might have. I guess there are people testing things just to be able to say, I developed a test πŸ˜„ AssetDatabase came alone my way yesterday too. Quite handy to setup a Asset scene where your graphics guy can just load a bunch of prefabs from a folder and get little gizmo updates when a prefab has not been saved/overriden πŸ˜„

humble charm
midnight violet
humble charm
midnight violet
keen cloud
#

Email email = new(this);

Why would this be giving object reference not set to instance?

#

as well as this
List<Email> Emails = new();

humble charm
#

u need to use new typof(this)

#

or somthing like that

keen cloud
#

vs is telling me i can discard that part

midnight violet
#

vs is telling a lot sometime

#

what is Email?

keen cloud
#

a class for emails

#

lmao

midnight violet
#

No joke!? πŸ˜„

#

do you have a constructor?

keen cloud
#

yeah i do

midnight violet
#

like, you wanna share any code or just let us keep asking? πŸ˜„

keen cloud
#
private bool IsRead = false;
        private bool IsHidden = false;
        public string Title;
        public string Content = "";
        public DateTime DateRecieved;
        public string AssociatedJobName;
        public Job AssociatedJob;
        public Email() { }

        public Email(string title, string content, DateTime dateRecieved, string associatedJobName)
        {
            Title = title;
            Content = content;
            DateRecieved = dateRecieved;
            AssociatedJobName = associatedJobName;
        }
        public Email(Job job)
        {
            DateRecieved = DateTime.Now;
            AssociatedJob = job;

            MakeTitle();
        }

        public Email(SubmitReturnValues returnValues)
        {
            DateRecieved = DateTime.Now;
            AssociatedJob = returnValues.GetJob();
            MakeContentWhenTestCasesPass(returnValues);
        }
#

Just needed to copy it

#

the one I am using is the submit return value constructor

midnight violet
#

Email email = new(this); what is this in this case?

keen cloud
#
public Email(SubmitReturnValues returnValues)
        {
            DateRecieved = DateTime.Now;
            AssociatedJob = returnValues.GetJob();
            MakeContentWhenTestCasesPass(returnValues);
        }
lament salmon
#

And what is MakeContentWhenTestCasesPass?

gentle topaz
#

surely there is an error line in the stack trace

midnight violet
#

And where is it crying about your null reference?

keen cloud
# lament salmon And what is ``MakeContentWhenTestCasesPass``?
public void MakeTitle()
        {
            Title = $"{RandomDialogue.InRegardanceTo()} {AssociatedJob.Title}, from {AssociatedJob.AssignedNPC}";
        }

        public void MakeContentWhenTestCasesPass(SubmitReturnValues returnValues)
        {
            MakeTitle();

            Content =
                $"{RandomDialogue.IntroGreeting()} {GameData.USER.Username},\n\n" +
                $"{RandomDialogue.GettingResultsBack()}\n\n" +
                $"{returnValues.GetTimeComplexityString()}\n\n" +
                $"${AssociatedJob.AmountOffered} {RandomDialogue.MoneyHasBeenTransferred()}\n\n" +
                $"{RandomDialogue.EndingGreeting()},\n\n" +
                $"{AssociatedJob.AssignedNPC}";
        }
keen cloud
#

inside itself

gentle topaz
#

you have to give us relevant information, because right now you have this entire system set up with random calls to random functions

keen cloud
#

yes its literally supposed to be random lol its just creating dialogue

#

imagine that as a string

#

thats all that is

gentle topaz
#

so what line causes the error

keen cloud
#

when I call it from inside submitreturn

#

"call"

#

create an instance

lament salmon
#

What line

#

number

keen cloud
#

public override void FormatOutputToEmail()
{
Email email = new(this);

        EmailDatabase.AddEmail(email);
    }
gentle topaz
#

a constructor can't cause a null reference, a line of code inside the constructor can

humble charm
#

ahh

gentle topaz
#

at this point I can only recommend logging values or using the debugger with a breakpoint

keen cloud
#

so odd

#

alright ill try

#

thank you

gentle topaz
#

probably not that odd

#

there is just something null somewhere

#

and that's it

keen cloud
#

its odd that it worked last night lmao

#

and i havent done much sinc e

gentle topaz
#

well, it will likely make sense when you find it

keen cloud
#

well how about the other one

#

foreach (Email email in EmailDatabase.Emails)

#

this points to this
public static List<Email> Emails = new();

#

and its saying its a null reference exception

#

how come

gentle topaz
#

impossible to answer that question

midnight violet
keen cloud
#

i use just the new() abundantly in my code

#

so that wouldve been odd

gentle topaz
#

it's the same

#

just shorter

keen cloud
#

yeah

midnight violet
#

sometimes I felt c

#

c# was a bit picky, but I guess it was just me πŸ˜„

#

so did you use breakpoints to see, what values are actually null?

keen cloud
#

i just call it onenable

#

the foreach

#

even if its empty i create a new list of objects

#

idk how it could be null

gentle topaz
#

okay, but that's kind of unrelated

keen cloud
#

but thats when its being thrown

#

calling it from onenable

gentle topaz
#

if you use the breakpoint and the debugger, it will literally tell you every value in your program at the time of the error

keen cloud
#

you enable breakpoints through this?

gentle topaz
#

did you read it?

#

enable debugging if you want to use the debugger

keen cloud
#

just confirming

#

first time ive used this

#

in unity

keen cloud
#

well it is null

gentle topaz
#

is the declaration the only place you set Emails to a value?

#

like there is nowhere you are somehow setting it to null, or setting it to an existing list (which could be null), etc?

keen cloud
#

youre right apologies its null cause i tried to load an empty json into it at startup

#

onto the first null

#

the other null

gentle topaz
#

ah, that'll do it

keen cloud
#

and thats what i added before i went to bed too

#

all lines up

#

lmao

gentle topaz
#

always does

midnight violet
#

why isnt there a null emote btw πŸ˜„

keen cloud
#

me fixing this seems to have also fixed the other thing

#

cause apparently C# doesnt like .Add()ing to a null list

#

lmao

midnight violet
#

adding to nothing, I would not like that either πŸ˜„

keen cloud
#

alright well thank you guys

#

had to talk myself through it too

#

was stumped for a bit

#

also thanks for pushing me to use the debugger lmao

gentle topaz
#

yeah it's pretty easy, very helpful sometimes

#

saves a lot of time you would usually spend logging things or whatever

keen cloud
#

i just have infinite unit tests lmao

#

like 100

gentle topaz
#

those are nice too, although for different reasons

keen cloud
#

yeah thats what ive been using as my debugger

#

lol

#

just testing that it works exactly as it should

pastel lodge
#

TextureImporter.spritesheet has become Obsoloete, the documentation tells me to use "UnityEditor.U2D.Sprites.ISpriteEditorDataProvider" instead. Does anyone have experience with this, or even better a link to a use-case example? Thanks in advance.

bold vine
#

Is there a way in Unity, to get the main UIController on iOS?

silk trench
#

I'm a very experienced user with Unity and C#, and I'm trying to make a fast paced multiplayer game. I've tried doing it before but every time I tackled a multiplayer project, it ends up becoming extremely non-scalable down the road and I give up because of the immense amount of refactoring that I'd have to do

#

So my question is, are there any recommended papers or artices that I could reference that cover the design strategies for a scalable multiplayer game?

fiery nebula
#

Hey, I have a problem with a raycast system reflection. I have a gameobject which emits a raycast in a certain direction, when the raycast hit an other gameobject which has the layer "Mirror", it should reflect it as light. However, i got this reflection :

#

(and their are to magenta raycast, not one)

#

so i don't know why it's doing that

orchid marsh
#

!code

thorn flintBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

fiery nebula
#

I edited

#

(sorry for the comments, i'm french)

orchid marsh
#

Is the rock the mirror or the white block?

#

I'm assuming you meant "and there are two magenta raycasts, not one".

#

What's happening and what's the expected?

fiery nebula
#

The white block is the mirror yeah

#

(i also tried to delete it, it's a non collision object)

#

I expect to have the reflection on the point that the red raycast hits the white block

#

like a laser

#

And so on if the reflection hits another white block which has the mirror layer, it does the same

timber flame
#

I keep stocks in a dictionary with ProductType as a key and StockData in value. StockData is a mutable data container (class). The fields AvailableCount and ReservedCount can change/increase/decrease.
When the number of an item changes (available or reserved count), an event is raised. The argument of this event is old (before) and new stock data (after). I create a new instance for each old and new stock data argument and then raise the event with them. Should the event argument be an immutable struct? or even StockData as a value in the dictionary.
Generally, data container as value in a dictionary should be struct or class.
and what about arguments (old and new) in OnValueChanged when they are not simple primitive types (int) while they are data container, some values packed in a struct/class type

orchid marsh
#

Where is the origin of the raycast?

timber flame
orchid marsh
timber flame
#

Origin is the beginning of the ray/line

fiery nebula
#

i can rotate the mirror like i want, but even the 90Β° is not working

orchid marsh
fiery nebula
#

here if i zoom in

orchid marsh
fiery nebula
#

yeah, the issue is the offset, i want the reflection to be directly on hit.point

#

yeah, i debug.log it

timber flame
#

Can you show me its collider 2d?

fiery nebula
#

there it is, (i need it to be triggered, idk if it's the issue)

timber flame
timber flame
wild patio
#

Hey so I am new to unity and I am trying to make a simple flappy bird clone as my first project, I ran into a issue could anyone help me?

fresh salmon
wild patio
thin mesa
#

don't crosspost. you also didn't ask a question

wild patio
fiery nebula
#

I reset the variable Physics2D.queriesStartCollider to true, because with this variable at false, it makes my player lag

#

So now, the raycast is like this:

thin mesa
fiery nebula
#

kinda weird :/

fiery nebula
thin mesa
# wild patio bro you silly

and you're wasting everyone's time by not actually providing any details about your issue and also asking in the wrong channel. go back to #πŸ’»β”ƒcode-beginner where your question belongs and actually fucking ask a question instead of asking "can anyone help" with no details

wild patio
fresh salmon
#

That small green icon to the right of your name shows you're new here

timber flame
#

put your code

fiery nebula
orchid marsh
#

He did

#

Debug.DrawRay(hit.point, deflectDirection, Color.magenta, 1f); and Debug.DrawLine(pos, shoot, Color.red, 1f);

#

Initial red is with draw line and further magenta is with draw ray

#

Not sure why deflectRotation is necessary as hit.normal should already be the deflectDirection

fiery nebula
#

i'm trying to

#

with hit.normal i got this

orchid marsh
#

As the normal to the ray would be the reflected ray and point would be the surface contact.

fiery nebula
#

I just did that instead of deflectDirection

#

but it does the result i sent just before

orchid marsh
fiery nebula
#

?

orchid marsh
#

This implies the red should be a horizontal line

fiery nebula
#

ooh

#

u mean the red line is not good drawn?

#

(sorry for my english xD)

orchid marsh
#

As red is generated using some other means, you've likely asked the data

fiery nebula
#

the data of what?

fresh salmon
#

Small side note, mirrors don't reflect along their normal. If the light comes at an angle it'll get reflected wrong. You should try Vector3.Reflect if you haven't tested it

orchid marsh
#

Where drawn line takes two points, draw ray takes a point and a direction.

fiery nebula
#

I tried to draw my red line like this

#

but... it happens something weird

orchid marsh
fiery nebula
#

yeah but look now with the new code, the line goes on the left

orchid marsh
#

Implies you're assuming shoot is a ray when it's not

fresh salmon
#

DrawLine expects two points, not a point and a direction

orchid marsh
#

Shoot is simply a point

fiery nebula
#

oooh

#

ok

sly grove
# fiery nebula

DrawLine expects two positions. You provided a position and a direction

fiery nebula
#

yeah yeah i know

fresh salmon
#

Easy fix, DrawLine(start, start + dir, ...)

orchid marsh
#

Something is off - I'm on mobile so reading, zooming in, etc takes some time (slow responses)

fiery nebula
#

I don't really know what is the "dir" in my case

fresh salmon
#

Normal of the mirror

#

Or ray.direction here

fiery nebula
#

like so?

fresh salmon
#

ray.origin + ray.direction for the 2nd argument

fiery nebula
#

wait i'm too stupid xD yeah

#

i just get it

fresh salmon
#

Or you can use .DrawRay which takes a position and a direction, whatever is clearer to you

fiery nebula
orchid marsh
# fiery nebula

Nothing is wrong with draw line from what I've seen. But you're feeding the new ray object two points, not a point and a direction

fiery nebula
#

It stills doing a horizontal magenta ray

orchid marsh
#

The second argument for Ray should have been a direction

#

Direction is calculated with final position minus initial position, normalized.

fiery nebula
#

Yeah, that's why i have a little red line now

orchid marsh
#

Meaning, where you hit minus where you've started, normalized

#

Dude

#

I said the issue is with what you're feeding ray, not draw line

fiery nebula
#

u mean this?

orchid marsh
#

Yes

fresh salmon
orchid marsh
#

Shoot is not a direction, it's a position right now and wrong

fiery nebula
#

So

#

shoot - pos?

#

as second arg?

orchid marsh
#

(half asleep πŸ˜›)

fiery nebula
#

(i'm kinda braindead rn xD)

#

just did that

#

oh

#

ok

#

wait

#

nevermind, still not working

orchid marsh
#

Consider using draw ray and not draw line to make the code uniform

fiery nebula
#

ok, so now i have this :

#

with a ray, calculated by:

sly grove