#archived-code-advanced
1 messages Β· Page 39 of 1
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);
}
}
Where are you using gridGame in MoveController?
Wait let me fix it
Inside CanMoveToTile
Anyone? 
This is fine, seems like your MoveController has to know about grid to perform movement.
so no other way around?
What would be the reason you are seeking for other way?
Are you planning to reuse MoveController somewhere outside grid?
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
You need to think about what you'd gain from decoupling first, "just to decouple" would be pointless.
You could make grid as interface, or have base class for controller, etc, but if you don't plan to reuse and you think they will be used in same context, I doubt you need it.
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?
If it's something that's occurring due to low frames, it's likely something to do with dependency on delta time. In the above code, that would be what's in the if statement. Else the issue lies elsewhere.
else is just player jump handling and other stuff but the problem is like you mentioned in the if statement, but changing to fixedDeltaTime or lerping velocity and lowering it doesnt help
Depends on how you're using velocity. What're you doing with velocity?
just that player.transform.Translate(new Vector3(0, velocity, 0) * Time.deltaTime);
does changing to fixedDeltaTime here help?
No
yeah thought so
You could probably resolve this by doing the platform (ground) check after incrementing velocity instead of before.
I tried didnt work
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.
okayy will try thanks!
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
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.
yup exactly
Which might teleport you through the floor/platform
Or in your case, thankfully only jitter.
yea i should take this into consideration if im gonna be making all of these games without unity's built in system
Did this work?
wait lemme try
Assuming velocity relative to y is some large negative value
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 +
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.
ohhh yeah that makes sense
I'm guessing with subtraction if it's a positive value.
yeah ill give it a try wait
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).
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
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.
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
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
With good naming convention substitutes, basically:```
if currentPosY > bottomOfPlatform && nextPosY < bottomOfPlatform
currentPosY = topOfPlatform
velocity = none
...
break
(removed numerics and arithmetics)
Good luck 
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
That's to keep you above the bottom. To not shake, you'll probably also want to include checks for the top of the platform. cs if ((... > ... && ... > ...) || (... > topOfPlatform && ... < topOfPlatform)) ... @blissful dagger
You might wanna do that in onStartClient and check for isOwner if it only happens on the controlling player
have you looked at the moremountains 2.5d corgi engine asset? it is hard to implement collide and slide physics yourself unless the purpose is education
is this unity's localization package?
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!
You'd first need to be able to read out when beats happen in the playing audio. The simplest approach would just use the BPM.
Then you need to get the time at which the input occurred vs how close you currently are to the last or next beat.
You'd need to remember when the track started playing, and can read the current track time from AudioSource.time.
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?
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?
sorry I wasn't online . yes it is
playfab is the most polished
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?
now i did the correct question about it eheh π
i have deleted and reinstalled the localization package and i still got the same thing.. the locales aren't being seen
when ou say online gameplay
do you mean realtime multiplayer?
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...)
you want to make a realtime multiplayer webgl game?
and also being able to create matchmaking i guess using Photon for what i see atm
for now i export it as webgl game but i will put it at steam
for a desktop application
okay got it
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)
choosing photon will be the most likely to get you to a working, realtime multiplayer game
Alright ! realtime situation seems OK
Now about database? (firebase?)
I will create a login/register interface before being able to create characters in the account
i think you would use whatever solution photon provides
i can use photon for the multiplayer realtime and firebase to save player information?
or if i use photon i can't use firebase?
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
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?
based on the screenshot, it looks like this is a top down persistent world realtime multiplayer rpg, like ultima, right?
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
photon isn't all about server host for matchmaking?
photon offers a lot of services
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
but it have a free version to try i guess
okay what i am really saying is
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
You could also try to look into Unity Gaming Service. They have been pushing a lot on this recently, it would be a shame to not even consider the option.
Realtime (https://unity.com/products/netcode)
Hosting and others (https://unity.com/solutions/gaming-services)
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
am i making sense?
yes guys you both make sense about it
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.
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...
You start by copying others, like artist start by copying other art.
No, that is a completed project.
what is netcode at all?
it enables people to create accounts?
or deals with real time gameplay?
Netcode is equivalent to Photon. It is Unity in house solution that has been recently launch.
Ok so netcode ables me to create a kind of matchmaking right?
no it does not
if you need to talk to someone via voice you can do that in private
That is a separate service. You should look into it by yourself. Now, if you have any more question, try to hit #π»βcode-beginner.
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
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.
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
Not fixed but my current understanding is 2022.3 should be LTS in March this year
tbh if you are on 2020 LTS I'd stick with that unless there is a pressing reason to upgrade
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
If I'm not wrong the grid turning blue is just for visuals? Like pathfinder can access the blue areas and doesn't affect the gameplay
Object that's finding path will only be able to move in blue area and anything outside it is unreachable
Yup it's for visuals
Not exactly
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
You didn't use the player node
You literally display all the grid in blue
if( n == playerNode)
{
Gizmos.color = blue;
Gizmos.DrawCube(....);
}```
Inside the foreach ( It's pseudocode )
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
OHHH
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)
have you somehow filled your grid with references to the same Node object?
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)
nope
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
how is your Node class/struct checking equality?
Sounds feasible and simple enough, thanks.
I'm a bit worried about getting out of sync.
You'd have to test it, but you can't really desync "more" after time, since the elapsed time is accurate, so the offset into the song should always be correct
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?
it isnt checking equality
its merely going thru each node, checking whether that node is walkable or not and whether the player is on that node or not
your question is why all nodes are being drawn as cyan?
you linked the code that is drawing those cyan nodes, in OnDrawGizmos, and you have playerNode == n
this code really isn't doing very much, there's limited things it can be
Yep
but thru debugging it appears that this part of the code is what is causing the problem
your question might be better helped in #π»βcode-beginner
I'm on 2021.3.3 (so upgrading to the LTS of 2021.3 seems like the most obvious choice.. and in fact, it was, the upgrade was completely painless, much to my relief)
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.
what is best way to find closest enemy for rogue like game? just thinking about performance.
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
This is a #archived-code-general question really
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.
You do not query the result, you might have an issue with your build.
It builds fine in the editor, not sure why it won't work from the command line
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?
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?
who knows
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?
(crosspost from #archived-shaders, which I've already replied to)
The errors I see on your screenshot (please dont do that again, post code here or a link to a paste website) are not advanced coding... you should def look into basic c# syntax maybe with Unity learn courses first.
Hey guys, is there a way to get these values from the project settings via script? OR, alternatively, get these values from the dashboard??
I guess, you have to paste them manually there?
Actually, not necessarily. Just created an empty project, initialized new project ID and turned on the Ads service, these two fields are filled out automatically. But my question is basically about how I can get these values from an editor script.
OMG
Thank you so much
Facepalming so hard
Yeah, just know what to google for π Its in playersettings, that has its own implementatino to be used in code π
you just googled unity ads settings api or smth like that? or you knew that there's this api already? teach me sensei
I knew its in playersettings, searched for that, inside the docs page searched for Advertisement and that led me to the settings of advertisement on the left side of the docs classes overview π
Right, right, ok I see, thank you so much, I was beginning to think such API doesn't exist, phew!..
You are welcome π
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
Ignore library folders π
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...
What happens if you Get the id? is it only returning the ID or more ifnormation?
If itβs stored in PlayerSettings, you can open that file and see whatβs used there, decent chance that will be it.
it's just an empty string, that's all
At worst you can use reflection/parse the file manually.
So both, GetGameID and GetPlatformGameID or how its called is returning an empty string?
ooooooooohhhh that's an interesting one
OMG you are so right
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
Thanks for letting us know as the docs are msising that part π π
Thanks for the help, guys!
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)
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?
hey, this tutorial might help? https://www.youtube.com/watch?v=sU_Y2g1Nidk&ab_channel=DestinedToLearn
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...
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
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.
I guess if you set a value on one platform setting it will persist until you change it to what you need. Makes sense to me
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
why do you think it's because the URL is long
Is the url maybe on another server, do you have a crossdomain xml setup so your applicatino is allowed to access the resource?
I cut the url in half so it started working
If you cut the url in half you're now accessing a different resource
it is on a server yes, I uploaded the webgl version on a server, and the link has some arguments for us to use
it's not about the length
yes btu the app doesn't start until I delete lots from the link
Do you get any error code from the server? 505 or something?
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
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
Start by not crossposting
Whats the issue @sly grove
this is what I am getting , there's no code or anything
Open Developer tools in your browser
you are posting on two channels about the same issue and clearly posting a not advanced code issue in this channel.
three channels actually
what do I do then
started in #π»βcode-beginner , where the question no doubt belongs
Wait 4 channels! Also posted in #π»βunity-talk
DataArray Structure
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?
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
I would go with the enum approach. No unneeded inheritance just to get another type. But that really depends on your objects. Do they differ a lot or just firing different events because of their type.
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
Yeah I'd go for the enum approach as well
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
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?
Because here they ask the stream index as the input:
https://docs.unity3d.com/2020.1/Documentation/ScriptReference/Mesh.SetVertexBufferData.html
So I should split my data in 3 different structs to pass to the SetVertexBufferData? (In the context where I use all vertex attributes)
What's the context here? Are you trying to generate a valid mesh that can be skinned by Unity's skinning system?
Yup. But I just realized that when using 3 different streams, I need 3 different vertex structures to pass to the SetVertexBufferData call
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
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
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
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 π
Are you using Unity test framework?
Add the TextMeshPro reference to the test asmdef
how did he do this π
Where are you going to publish your game?
webgl
SO on a website or unity's show case site
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
it should be referenced previously
unless something else needs to be done
What about your main assembly that contains EditJobDatabaseMonoBehaviour
Does your test assembly references your main assembly?
Also you probably wanna do new GameObject().AddComponent<MyComponent>() not new MyComponent()
I tried this as well I think I saw that on a forum
How would you check this
@short fog Stop crossposting
but they didnt help me, so i think ask this question to this server
beginner couldnt help me, general couldnt help me...
You should have them separately
hi
You won't want nunit in your build
@short fog bro i love you. You are pro you coding a best game.
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.
yeah this is my edit mode one
XD
ok thx
you were kicked by team decision
also apologies im just in class and am not focused 100% on your help may i come back later? i feel bad lmao
So this one should also reference the Unity.TextMeshPro
ah okay
:(
thank you
No problem
no problemo
If you're just here to shitpost, I suggest you leave.
who are you?
i am metin2
!mute 645975394369011712 3d You can come back and try again. Or leave, it's up to you.
Hamitttt#9623 was muted
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?
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
Ooh! That's convenient! thank you so much!
just to be safe, 0 is considered positive in this context. correct?
so id>=0 is an asset ref?
Docs don't mention it, but I would say it cannot be 0 ever
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)
Oh recent docs says it's never zero, was on an old page
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
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!
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
I have specific type for each Building, so in my mind, defining enum to check type is pointless, kinda duplicated.
When a building is added/created, based on each type, it should handle different procedures
Yes, so edit.code is null, since the component just created without any pre-set values
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
Well why do ask for the opinion if you already decided. I just wrote my opinion about issues you will run into when making everything inherit from Building just to get variations that will do the same
As said, it depends on your setup.
I try to set it there to something that is not null
but when I set it it gives the error
like when I set code.text to jobdata.read
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!
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.
Just use a Dictionary<Vector2Int, Troop>
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
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 i wont do that, instead ill have a Troop getTroopAtPosition(int position) function in the troop class)Map object that has a copy of the reference to the troop.
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
what about em
how do they compare to classes and regular objects?
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
oh but theyre otherwise the same thing?
they're not the same thing
in any sense
I don't really understand what you mean by that
well an object is an instance of a class, so is a scriptableobject also an instance of a class?
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.
alright, thanks
Yeah So the code is null, where are you setting code?
This might be a lack of understanding then lol Iβll try to look into it
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?
is this at runtime or editor
Runtime
dictionary is not serialized so will not save in the inspector
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
@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
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
rubber duck
Rubber duck indeed π
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
"__Internal", createPaymentRequest parameters are wrong
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
I'll give it a shot
Are there any good plugins that implement Apple Pay?
How do I print a value to the log? Itβs been a while for me.
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?
A tool for sharing your source code with the world!
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).
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...
If anyone is familiar with Render Streaming in Unity. Please can you look here: https://forum.unity.com/threads/unity-render-streaming-introduction-faq.742481/page-22#post-8752759
I guess that depends on how important immutability is to you. I personally don't see any issue with it.
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?
store a struct that contains the reference and a enum representing the joint type
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.
Do you need the specific fields/properties from specific joint types? Can you not just use Joint fields?
Yes, I need to be able to access derivative type fields.
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
that could work, thanks!
Has anyone successfully created a plugin for Apple Pay? Not for IAP, since we're working with physical products.
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
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
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.
doesn't make sense
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
unless you just mean this:
https://openid.net/specs/openid-connect-basic-1_0.html#TokenOK
OpenID Connect
Basic Client Implementer's Guide 1.0 - draft 42
yes but I need to get that token first
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
currently only the web browser can see the token
this is an auth request, we're already authed
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
ok so the request is being made in JavaScript?
Is that what you're saying?
and you want to communicate the token to the Unity app running in the page?
all of the login stuff is currently done on the JS side yes
the unity app is standalone elsewhere
but I imagine it would be p much the same with webgl vs mobile native
it's not webGL?
nope
In webGL you'd do this:
https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html
"Calling Unity scripts functions from JavaScript"
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
damn that looks super helpful too
am I actually able to export an AR app to unity WebGL?
it uses ARCore and stuff
you could have your Unity app listen over IP and just send it like that
that would require port forwarding without a websocket iirc
port forwarding? Nah
Nothing leaves your computer
how can it listen without port forwarding
this backend will be hosted
I'm confused about where this all is running.
its written in nodejs it cant run on the user's phone
yep
ohhh no sorry the backend is node
backend is node but we're talking about a client, no?
backend in node, unity app that will run on a phone
yep the backend is all setup, its just a few endpoints that open a login screen and get a token using auth0
ok so there's no Javascript. Unity is making requests directly to/from the nodejs server
yes
Ok so I'm confused what the question is exactly
you were talking about a website here
what website is that
how do I get the token from the backend into unity, and secondly, how do I then use that token to access the endpoints
literally just the auth0 page
yes
well thats what I hope to do, atm im testing it on PC
either way a web browser opens to perform the login
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
that seems quite complicated icl, I'm not sure how i would implement this in code
in code it's basically just look like:
- send an auth request
- server responds with the token
in between those two the login happens unbenownst to your Unity code
1 and 3 are the request and the response
by send an auth request do you mean opening the browser to let the user login?
I hadn't put much thought into this, I was imagining there's a function in unity just to pop it open or i could use a plugin
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
reading this now, seems useful https://auth0.com/blog/complete-guide-to-nodejs-express-user-authentication/
https://www.youtube.com/watch?v=X1BrOOHFwGc looking into this
auth0 docs page is down π¦
this was the original tutorial I followed to make the code I have currently https://www.youtube.com/watch?v=QQwo4E_B0y8
the docs being down does NOT help matters
I have no idea how to connect this api thing to my actual running backend
If you are just looking at creating a login system and tracking user sessions, depending on how critical your application is with security. You could deploy your nodejs application on a VM and host a local mongo db and use simple JWT system for session exchange in your api.
the docs pages are still down
I'm using express-openid-connect instead of "jwt", should I be using that instead? my code is linked above, what should I change?
again the docs being offline (500) for me is super annoying
There's no "one" way. I guess it just depends on your requirements.
I looked at your code and I'm not sure why you are even using express. You dont have anything set up for it. If you are just creating an API for an Auth system for your game, then all you need is nodejs. Express is primarly used for serving static content using a render engine like EJS
I was just following what the tutorial said to do, to create a login screen with auth0
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
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"
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
also, if this will work on mobile I can give this a go for making the web requests that I need https://auth0.github.io/auth0.net/
What exactly is the problem you are facing. Is it unity related or a design/implementation question ?
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
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.
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?
Just you
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
https://auth0.com/docs/api/authentication#get-user-info this returns unauthroised
yall get that feeling where every link on google is purple and you still have no answer?
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
What are you trying to do ? What you are doing make no sense in my eyes. You might want to look into Camera.targetTexture if you want to "write" in a RenderTexture.
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
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.
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.
you can find an oidc compatible auth asset for desktops on the asset store
im doing this for a mobile app and dont wanna buy anything
https://www.youtube.com/watch?v=jFitx8gf7rA looking into this
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...
i need to separate my "webapp" and my "apI"
what is your goal?
@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?
Im trying to avoid doing this
is this for a thumbnail?
like what does the app do?
i already explained this
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
okay
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
this is actually really easy so i don't understand what your obstacle is
well the obstacle is ive been trying this for 2 whole days and havent managed
its difficult and im new
okay
well this makes no sense
why not
it sounds like you want the profile information
yes, inside unity
and also an auth token so i can access secure endpoints, in this case making social media-type posts
i get it
so listen
have you been able to login yet or no
do you have that working?
yes
are you sure?
what do you mean by this
if you are logged in, you have 3 tokens
- an id token
- an access token
- a refresh token
https://www.jamesqquick.com/blog/the-easiest-way-to-add-node-js-user-authentication/ I have this essentially
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?
I'm not sure, I can access the id token
lol
is the refresh part of req.oidc
access the id token is just funny sounding
i literally followed that tutorial
i can retrieve it then lol
but idek what a refresh token is
why cant I just get the accesstoken when logged in as a user? thats what im wanting to give back to unity
and hence this tutorial is not helpful to you
damn π¦
i think you are doing something pretty complex
without using an appropriate asset
which will help you a lot
is the asset free and does it work on mobile
i don't know. you should look for one
i did
i believe auth0 has a unity package
it doesn't erally make sense to login while wearing a headset
and it uses an entirely different system
is this a quest?
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
i see
its just a normal unity app
https://auth0.com/docs/quickstart/native/android so this, but in unity
i want the app to pop open a browser, user logs in, the game retrieves that login data (access token for api)
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
what is playfab? will it work with my current backend code
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
alright, this seems to work just how I want it to
I need to make some basic UI but it still works great
can you call a method when list.Add is called?
Not sure what you mean? You mean if the list.add is also a delegate that fires an event?
yes I want to subscribe to list.Add event if there is one
I do not think there is one, but you can just hook into the moment you add something, dont you?
yes i can just wanted to keep my code clean
Ah got it. Unfortunately I think we are out of luck. Been in that situatin before, always just created my own delegate for that.
ty for info I think I will just use inheritance and make List with delegate instead
Ah like a custom List class? Sure, why not π
Wouldn't an Extension method be better?
(@humble charm)
You could even overload the same method probably
How would you go about it adding the delegate to that list? Curious for future projects π
Let me try
Like with an extension you would need to pass in the delegate or rather the action/event to callback, right?
I mean it kinda depends what he exactly means
Because I first thought it was just do an additional thing upon adding
Yeah he wants to call a delegate when a List is being modified I guess
But if he specifically wants an event bound to that specific list then a custom class might be needed yeah
Yeah but is that event bound to that list or is it for every list
I guess bound to that list. But well, only he/she knows π
Well it really depends on the context if Extension methods are applicable here
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
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
I couldn't figure out how to just make the out Action a new Action so I made a class that literally only has an Action in it
(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?
Doing lunch, will look into that later for sure! π
Ah fair enough, have a good lunch!
That reminds me, I should probably have lunch as well so ima do that now π
Is there already something that does what you want ? Talking about the keyword event. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/event
The keyword event wouldnβt really do much in this scenario
Yeah, srry was just trying to figure out what you were doing. It doesnt seem well executed.
It depends on the context if youβd want it or not
Probably isnβt, itβs just some theory crafting around what somebody wants
You want to trigger an event when an object is added in a list ?
But he wasnβt very descriptive so I just was making some random code
Yeah pretty much
At least that is what we think he wants
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.
Thatβs why I suggested a custom class for lists with events is probably better
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
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.
Yeah as I said before, it really depends on the context
Which we werenβt given a whole lot of
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)
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
How would you do it if you had to use extension methods?
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);
}```
If you would inherit from List, would it be something simple as this?
[System.Serializable]
public class CustomList<T> : List<T>
{
public Action addEvent;
public CustomList(Action evt)
{
addEvent = evt;
}
public new void Add(T item)
{
((List<T>)this).Add(item);
addEvent?.Invoke();
}
}
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?
if it is possible.
Otherwise you create a wrapper
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 π
How about that command shortcut here? https://support.unity.com/hc/en-us/articles/360044824951-I-need-to-start-Unity-with-an-environment-variable-s-set-how-can-I-do-that-
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 π
that exactly what I used. by sample you mean its good approach right ?
I at least dont know a better approach π And I quite like this and will iuse it myself when I figure out, why the inspector is not showing the list, guess the editor needs to be set manually as its inheritance
that is not a big deal tbh I can work around that
Let me know when you implemented the inspector (if you going to), so I can lazily copy paste it π
Email email = new(this);
Why would this be giving object reference not set to instance?
as well as this
List<Email> Emails = new();
vs is telling me i can discard that part
yeah i do
like, you wanna share any code or just let us keep asking? π
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
Email email = new(this); what is this in this case?
this
public Email(SubmitReturnValues returnValues)
{
DateRecieved = DateTime.Now;
AssociatedJob = returnValues.GetJob();
MakeContentWhenTestCasesPass(returnValues);
}
And what is MakeContentWhenTestCasesPass?
surely there is an error line in the stack trace
And where is it crying about your null reference?
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}";
}
when I call it from the submitreturn
inside itself
you have to give us relevant information, because right now you have this entire system set up with random calls to random functions
yes its literally supposed to be random lol its just creating dialogue
imagine that as a string
thats all that is
so what line causes the error
Not when. He asked what
What line
number
public override void FormatOutputToEmail()
{
Email email = new(this);
EmailDatabase.AddEmail(email);
}
a constructor can't cause a null reference, a line of code inside the constructor can
ahh
at this point I can only recommend logging values or using the debugger with a breakpoint
well, it will likely make sense when you find it
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
impossible to answer that question
Did you try to use new List<Email>(); ?
i tried it, same error
i use just the new() abundantly in my code
so that wouldve been odd
yeah
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?
i just call it onenable
the foreach
even if its empty i create a new list of objects
idk how it could be null
okay, but that's kind of unrelated
if you use the breakpoint and the debugger, it will literally tell you every value in your program at the time of the error
you enable breakpoints through this?
well it is null
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?
youre right apologies its null cause i tried to load an empty json into it at startup
onto the first null
the other null
ah, that'll do it
always does
why isnt there a null emote btw π
me fixing this seems to have also fixed the other thing
cause apparently C# doesnt like .Add()ing to a null list
lmao
adding to nothing, I would not like that either π
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
yeah it's pretty easy, very helpful sometimes
saves a lot of time you would usually spend logging things or whatever
those are nice too, although for different reasons
yeah thats what ive been using as my debugger
lol
just testing that it works exactly as it should
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.
Is there a way in Unity, to get the main UIController on iOS?
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?
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
!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.
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?
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
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
Where is the origin of the raycast?
What do you mean where?
Not referring to you
Origin is the beginning of the ray/line
His original illustration gives no idea whether it was from the right or left of the screen.
What's the issue? The offset?
yeah, the issue is the offset, i want the reflection to be directly on hit.point
yeah, i debug.log it
Can you show me its collider 2d?
It is perfect :/
No, it works or does not work, that's all
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?
Don't cross-post, please keep your question in one channel
#π»βcode-beginner
also #854851968446365696 to see how to ask a question
I put one in code beginner and no one responded
don't crosspost. you also didn't ask a question
did you read my post? XD
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:
again, #π»βcode-beginner and see #854851968446365696 for how to ask a question.
bro you silly
The issue is the offset yeah, and on the screen i just sent, u see that it just reflect to its own
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
wow someone got a lil toasty, noneed to throw a goo goo ga ga baby fit
That small green icon to the right of your name shows you're new here
Take some time to read the #πβcode-of-conduct and #854851968446365696 before posting
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
As the normal to the ray would be the reflected ray and point would be the surface contact.
I just did that instead of deflectDirection
but it does the result i sent just before
Maybe the days being fed after red is incorrect?
?
This implies the red should be a horizontal line
As red is generated using some other means, you've likely asked the data
the data of what?
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
Where drawn line takes two points, draw ray takes a point and a direction.
Implies you're assuming shoot is a ray when it's not
DrawLine expects two points, not a point and a direction
Shoot is simply a point
DrawLine expects two positions. You provided a position and a direction
yeah yeah i know
Easy fix, DrawLine(start, start + dir, ...)
Something is off - I'm on mobile so reading, zooming in, etc takes some time (slow responses)
I don't really know what is the "dir" in my case
it's ok
ray.origin + ray.direction for the 2nd argument
Or you can use .DrawRay which takes a position and a direction, whatever is clearer to you
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
It stills doing a horizontal magenta ray
The second argument for Ray should have been a direction
Direction is calculated with final position minus initial position, normalized.
Yeah, that's why i have a little red line now
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
Yes
Shoot is not a direction, it's a position right now and wrong
Not certain as my brain isn't functioning correctly right now, try it 
(half asleep π)
(i'm kinda braindead rn xD)
just did that
oh
ok
wait
nevermind, still not working
Consider using draw ray and not draw line to make the code uniform
what is shoot?