#archived-code-general
1 messages ยท Page 351 of 1
Use a LineRenderer and raycasts
bro can somebody please make me an anticheat for my game people have my apk and have all moderator items
I am using Raycasts, I'm mainly trying to write the logic for the script to scale down the Laser Sprite if the ray hits an Object in the middle that's not a Player
If I use Line Renderer, will I be able to use it with my Sprite?
I'm mainly trying to write the logic for the sprite to scale down the Laser Sprite
I mean isn't this dead simple? You position it in the center between the laser emitter and the hit point of the raycast, and just set the scale according to the raycast hit distance
I tried, but I'm not sure if it's correct, the output is crazy
void UpdateLaserBeam()
{
// Cast a ray from the laser spawn point to detect ground objects
RaycastHit2D hit = Physics2D.Raycast(spawnPoint.position, spawnPoint.right, 100f);
if (hit.collider != null)
{
float distance = hit.distance;
GameObject laserBeam = transform.GetChild(0).gameObject;
laserBeam.transform.localScale = new Vector3(distance, 1, 1); // Scale the laser beam to the distance
laserBeam.transform.position = spawnPoint.position + spawnPoint.right * distance / 2; // Position the laser beam correctly
}
else
{
GameObject laserBeam = transform.GetChild(0).gameObject;
laserBeam.transform.localScale = new Vector3(100f, 1, 1); // Scale the laser beam to the maximum detection range
laserBeam.transform.position = spawnPoint.position + spawnPoint.right * 100f / 2; // Position the laser beam correctly
}
}```
"crazy" how?
Like it jitters a lot because it's being called on Update() and it's like the 2d version of z fighting
Like a toddler is drawing aggressively
that doesn't mean much to me. A video would be better
Okay, one sec pls
does your laser itself have a collider?
Yes
Your raycast is hitting the laser itself
you're not using a layermask
use Debug.Log to diagnose issues like this
You need to be checking what your raycasyt is hitting
Ohhh
if (hit.collider != null) {
Debug.Log($"Hit {hit.collider.name}");```
๐ Thank you, I'll try
It just says object
what does
If it says "Hit object" in the console then you have a GameObject in the scene named "object", and that's what it's hitting.
Tools.current = Tool.View;
When called from Editor.OnSceneGUI, why does this line throw the following error and how would I fix it?
The targets array should not be used inside OnSceneGUI or OnPreviewGUI. Use the single target property instead.
Sorry I mean, it's printing the names correctly
But it's not working correctly still
printing the names of what correctly? What change did you make that would make it work correctly?
RaycastHit2D hit = Physics2D.Raycast(spawnPoint.position, spawnPoint.right, 100f, LayerMask.GetMask("Ground"));```
The Objects it is supposed to be blocked by are all on LayerMask ground
ok so... what's going wrong with it now?
How could I subdivide a mesh at runtime? I want to have a square prism and be able to subdivide it into x amount of smaller squares
Still "jittering" like the video
Doesn't scale like intended
ok and... are you logging things? What is it logging?
Show the code, show the console
play the sound from a different object, or don't destroy the object until the sounds is done.
Or just use AudioSource.PlayClipAtPoint
does anyone know how to make a gun shoot?
yo
https://hastebin.com/share/iqalohasuh.java
I'm not logging anything because the tracking and rotating is working, it's just the sprite scale adjustment that is buggy, which you recommended to debug now and I complied.
The problem is probably with the way the function is being called in Update or something, or maybe the logic for the scale adjustment is wrong itself
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
You're logging this:
Debug.Log($"Hit {hit.collider.name}");
You should probably also log something when it misses
see what happens when the jittering is going on
Okay
Null
what's null
It causes a Null reference exception when the ray misses because it's not hitting anything
If it is handled, it prints("Null")
obviously... you shouldn't be trying to print the name of nothing
I meant print something like Debug.Log("The ray hit nothing");
Sorry I haven't slept much today
It did print null, is there a way to see the Ray as debug line? I will remove the scaling logic and see what it's actually hitting?
Yes, use either Debug.DrawRay or Debug.DrawLine
Thank you
And don't forget about its parameter, time
Just started a new project and Unity is being funny with me, any time I save in Visual Studio unity recompiles which is normal, the annoying part is that it displays over Visual Studio and for a chronic Ctrl+S user like me it gets annoying very quick, is there a way I can stop this?
It displays over Visual Studio
Does this mean, Unity's tab is put above Visual Studio's when you pressCtrl + S?
Yeah after a second or 2
This has never happened to me
First time for me and it's a Unity Version I was working on in another project
What version?
2022.3.32f1
Maybe ask in #๐ปโunity-talk, and I have no idea
ok
For player state logic, is it better to use a single data structure or classes that inheritance from each other to represent states?
there is no one correct way. It depends on the scope and requirements of your system
If it's relatively simple, just an enum and a switch statement are good enough
Fair point. My state machine is somewhat complex hense why I asked. I am currently doing some logic like this where each state corresponds to an enum and has an action attached to it.
I am currently just searching through this to find the state I want but I am worried that this won't be sustainable.
when you say "searching yhrough this to find the state" are you describing something you are doing as a developer to make code changes?
Or are you describing something your code is doing?
whats the best way to save and load gameobjects from a scene while keeping all of their scripts and variables?
- Create a data structure that holds all the relevant data you need to save
- populate that object from your scene
- serialize it and save it to a save file
for loading, do the reverse
The ladder. Well, I have a dictionary of the state data class. Whenever I want to assign a state I have the script search through the dictionary and return the corrisponding "StateData"
you do mean just accessing the dictionary by the key right?
Not actually "searching through the dictionary"
Yes. Of course
I always mess that up ๐ญ
What I am more worried about it how I store the state data rather than how I obtain it.
For non constant ones, I'll probably have to create new states directly rather than obtaining it through the dictionary. Such as states that represent unique moves per characters.
So I can construct them or use a class for parameters.
@leaden ice Thanks for trying to help me.
Instead of spending 2-3 hours on this problem, I should have just reused my Grenade/Missile Launcher Prefab and increased the fire rate and Missile Sprite
๐คก ๐ซ
Vector3 handsDirection = other.Hand.position - Hand.position;
targetRotation = Quaternion.LookRotation(handsDirection);```
Very simple yes
Why it does this
The gun seems to flip around when going to a certain angle
I believe that angle is precisely aligned with the negative z axis
Uh yeah?
Any of your public spell derivatives will automatically be able to access the base spell variables
If your IceSpell inherits from Spell you do not need to get any component
It is a spell
It can access the spell variables
Yes. If another script is accessing icespell, it can access all of the public base spell variables too
I'm confused. Can you share what this is for
Example
And I am telling you, that your spellCaster script can just access the spell variables
If you're storing the prefs as gameobjects, then don't do that, store them as spells
I think so. I wouldn't do that though
You can just store it as a list of spells, and it will spawn the prefab and give you your spell automatically
Hi all ๐
I'm doing a VR project that needs manipulation over meshes in runtime, i decided to use ProBuilder plugin for that.
now i'm facing an issue regarding extrude within face normals
it says my face normals are Null
so i computed faces normals once again and tried to add then but..
pbMesh.normals = normals; gives Property or indexer 'ProBuilderMesh.normals' cannot be assigned to -- it is read only ERROR
my game got modded by an apk how do i prevent this
please do not cross post
public Vector2Int GetTileGridPosition(Vector2 mousePosition)
{
positionOnTheGrid.x = mousePosition.x - rectTransform.position.x;
positionOnTheGrid.y = rectTransform.position.y - mousePosition.y;
tileGridPosition.x = (int)(positionOnTheGrid.x / (tileSize * playerUICanvas.scaleFactor));
tileGridPosition.y = (int)(positionOnTheGrid.y / (tileSize * playerUICanvas.scaleFactor));
return tileGridPosition;
}
Found the solution, it was fairly simple, and now i can just pass the raw mousePosition
// recursively find the root object
Transform root = transform;
while (root.parent != null)
{
root = root.parent;
}
// set the root object to not be destroyed on scene change
DontDestroyOnLoad(root.gameObject);
is this a dumb way to do this?
i want to force whatever root object the component is attached to be ddol
even if nested
https://docs.unity3d.com/ScriptReference/Transform-root.html
look at the docs and you can answer this yourself
oh i got confused by the name
is that the same thing?
you can directly access the root
it says the topmost transform?
i would assume that means the first object in the hierarchy of the scene the component is in not the root object that the component is attached to
did you read the 2nd line of the 2 lines that were on that page
(This never returns null, if this Transform doesn't have a parent it returns itself.)
yes i did read it i'm just not sure its what i want
if you're saying it is ill try it though
DontDestroyOnLoad(transform.root.gameObject);
so i can do this?
and that will select the highest object like this
yes its the same as what you were doing in your while loop
though honestly it seems weird that a child object is doing this logic
well the alternative is putting a script on the HUD where its only purpose is to make it ddol
currently the "HUD" object is just a canvas with no scripts
i tried the line of code, didn't work nvm forgot to recompile
sorry how do I make the enemy STOP where it has been hit, instead of sliding to the player thanks :))
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
when hit: speed = 0?
im assuming you're using built in unity navmesh and controllers and such
yup
for some reason audio random containers do not play on awake if they are instantiated
unity docs says that instantiating is equivalent to duplicating with ctrl + d but thats obviously not the case
How are you doing your audio? Prefabs?
audio source attached to notification object that is instantiated
set to play on awake
only plays sound if i drag in or duplicate with ctrl + d
awake must run before the object is instantiated, but if thats the case how does duplicating it work
is the audio resource actually assigned to the prefab or does it get assigned after you instantiate it?
its actually assigned in the prefab
show your code that instantiates it
Have you tried making it a prefab?
So are you instantiating that?
show ๐ the ๐ code ๐
the code is Instantiate(prefab) lol
public void CreateNotification(Notification notification)
{
var notifGo = Instantiate(_notificationPrefab, transform);
var notifText = notifGo.GetComponent<INotificationText>();
notifText.Set(notification);
}
for some reason there is a difference between instantiating and using the editor to create a new instance
what does that INotificationText.Set method do
Creates the text
nothing related to the audio, but
public void Set(Notification notification)
{
string colorPrefix = "<color=#" + notification.SenderColorHex + ">";
_text.text = $"โข {colorPrefix}<b>{notification.Sender}</color></b>: {notification.Message}";
}
nothing crazy that should affect how it instantiates
๐ค
i think this might be a bug actually - here it is with a normal audio clip
gonna check docs on random audio container..
well it's definitely odd that this is happening. one thing you could do that would not only solve this issue, but also reduce your performance impact is to have just one audio source for these and just PlayOneShot on that audio source when you instantiate (or retrieve from a pool so you reduce the number of objects being created/destroyed) the object
well tbh i think theres a way to just play a sound without an audio source but idk how that would work with random containers
Maybe. You should probably do AudioSource.play anyways.
but if you can replicate this issue in a blank project then submit a bug report because that behaviour shouldn't be happening
there is not. even the PlayClipAtPoint method (which is static) just instantiates a new AudioSource. just use one AudioSource component and reuse it for all of these notification sounds
and are you actually using .11
well then you need to update to get the fix
i guess its better than finding the bug and then it not being fixed yet
That's why you use LTS for solid projects
i mean, bugs can happen in LTS versions too
tbh i've had less problems in the unity 6 preview than i have in LTS
True, but it's more likely to run into a bug in a beta build
i want to see when this update came out
because i quite literally updated less than 24 hours ago
why did it download 10f then..
i went from 2f1 to 10f1
maybe outdated notification? (i downloaded from the update notification in the editor)
because that's the version you selected obviously. if you hadn't restarted the hub between the time the new version was released and the time you updated then perhaps the hub just didn't see the newer version
that might be it i haven't shut down my computer in a couple of days
finally an issue that wasn't a complete skill issue on my part though
I'm trying to get the white cube to follow the cursor on the screen but for some reason it's on an offset. Does anyone know how I can make it actually cast from the correct position?
Log the input mouse position, camera mouse position result and the actual camera mouse position.
Here's an example log. Original mouse pos, mouse pos in the rect on the desktop, and the final hit pos.
That should be a viewport point to ray
After converting it to a normalized position
Within the RenderTex
Is there something wrong with this snippet?
The gameobjects I'm trying to create are being spawned, but they're invisible. The base prefab is showing up appropriately and it's always z = -1 (in 2d), which works for similar prefabs I've made.
I really have no idea why I can't see them
private void OnDestroy()
{
if (currentLife < totalLives)
{
Instantiate(iceSpikePrefab, transform.position + topOffset, Quaternion.Euler(0, 0, 35));
Instantiate(iceSpikePrefab, transform.position + bottomOffset, Quaternion.Euler(0, 0, -35));
currentLife++;
}
}
Pause the game and inspect the objects in scene view
Likely they're just either not within view of the camera or just behind something else
I've tried that. Positions are where they should be, they're just invisible. It's driving me nuts ๐คฏ
It's probably behind something then
Tried this but it started going really wacky
As I said you have to first convert it to a normalized position within the RectTransform
And no that doesn't mean .normalized
It means dividing it by the width/height of the Rect
Oh I see
anyone got a tut for this https://www.youtube.com/watch?v=6PSLfRsN89g
but with OVR stuff
What up guys, in this video I'm going to show you how to make a really cool Hand Menu that will follow your left hand and only show when your palm is facing up ! Super handy to let the player easily tweak something without being too intrusive. Hope you guys will enjoy the tutorial. :)
โค๏ธ Support on Patreon : https://www.patreon.com/ValemVR
๐ S...
i am trying to add a hand menu like this but in a mixed reality game
It follows the mouse again but just like in the first clip I sent it's still at an offset. Idk if I just did it wrong again because I'm dumb tho.
Actually I'm wrong it's offset in a slightly different but more accurate way, not exactly like before.
Hello, not sure if this is quite the right place but i think its my best bet?
Im making a mod for a game which reads custom assetbundles and .dlls to allow additional usermade content to be added to it. Im wondering how i can include code from a unity package into a dll to submit to the game? I am able to do it with assemblydefinitions using custom scripts i write myself.
Pretty random but... in variables declaration, do you guys use private keyword with private members or just write them out like.. Obviously there are 2 approaches:
private RigidBody rb; // Clearer
Rigidbody rb; // Concise
So, what do you guys say is the best convention?
ah good news the game doesnt care about package code being included
I prefer skipping writing out private but we annotate private variables with a _ at the begining so that it is clear it is private anywhere in the class e.g _rb
Ahh yes I know this convention. I used to do that too but stopped for no actual reason. Do you think it's a good habit to do a _? I really want to adapt to set conventions ๐ซ
There is no spoon. Conventions exist so that larger teams can work together more efficiently. And each team evolves its conventions over time to best fit them
Hmm got it. Thank you! ๐
I used to prefix with the underscore character but it looks pretty ugly, so I now prefix private member variables with m_
I'm assuming you meant _ and m_. You'd just use what the team is comfortable with - which may change with every team.
Yep
lightning not working in 2d
I set it up correctly tho (wrong but like i followed a tut)
installed urp from package manager, made an asset, added a 2d renderer to the asset,
This is a code channel
how do I detail my urp not working when I specified what I did
#854851968446365696 on how to ask questions
Hi guys. Is this the appropriate place to ask how to achieve something specific with cameras, possibly camera stacking?
sounds more like something for #๐ฅโcinemachine
Thanks, I'll give it a go
Still haven't found a solution. Does anyone have an idea?
Hello guys, I want to vibrate an object left and right according to its pivot.
There is the RectTransform.pivot variable
how can i change the pivot point for the default triangle sprite. wont let me edit it in sprite editor cause its within unity and i dont feel like using an actual sprite just to test out an idea but i can see that the pivot is in the center by default however i cant move it
Duplicate the default sprite
Edit the copy
Hello, I was wondering while coding if GetComponent() is a costly action or not ? Should I cache the result as much as possible ?
thats actually pretty smart, thx man
can someone help me with this pls,
void Shoot()
{
if (HandHolder.childCount == 0) return;
HandHolder.GetComponentInChildren<HandScript>().Shoot();
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 direction = (mousePosition - shootStart.position).normalized;
RaycastHit2D hit = Physics2D.Raycast(shootStart.position, direction, weaponRange);
GameObject trail = Instantiate(bulletTrail, shootStart.position, HandHolder.rotation);
TrailScript tr = trail.GetComponentInChildren<TrailScript>();
if (hit.collider != null)
{
tr.SetEndPos(hit.point);
}
else
{
Vector3 endPosit = shootStart.position + direction * weaponRange;
tr.SetEndPos(endPosit);
}
}
my issue is that it shoots to a certain position, instead of shooting to the mouse position
I first tried making it shoot to it's forward by using shootStart.forward
but it only shot to a certain point (always the same point no matter where I moved
It's not really that bad but it's best to cache it when convenient
My Tilemap is really huge, despite having, as I think, a single Tile. Any way to make it smaller?
it works fine the first time but later on it doesnt wait the full 2 seconds, i can see it throught the editor with serialized field barely switching to -1 for like a milli second instead of waiting properly
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DragonFlame : MonoBehaviour
{
public float flameTurnOnTimer;
[SerializeField] float flameDirection = 1;
void Update()
{
StartCoroutine(DirectionSwitcher());
}
IEnumerator DirectionSwitcher()
{
yield return new WaitForSeconds(flameTurnOnTimer);
flameDirection = -1;
yield return new WaitForSeconds(flameTurnOnTimer);
flameDirection = 1;
}
You start a new coroutine 60 times a second. StartCoroutine will not wait for the previous one to finish!
Also WaitForSeconds is framerate dependent
i think i need to use startcoroutine auto in the start method right?
That's a solution, and you can put a loop in the coroutine method so it runs forever
fun fact. Start method already has a coroutine
IEnumerator Start()
ok so i started the coroutine in start function like you said and put the code inside directionswitcher in a loop but now its all buggy and doesnt work
im not too good at making loops but the one i made was the classic
for (int i = 0; i < 2; i++) {
}
I have to go, someone else will take the lead
alr cya
"its all buggy and doesnt work" is not very descriptive anyway
why use a for and not a while ?
its the only loop i know of tbh
time to learn
agreed xd
for(;;)
Visual Studio automatically fills in loops on double Tab, its very good
Why does this happen
too much coffee?
Vector3 handsDirection = other.Hand.position - Hand.position;
Vector3 gripsDirection = other.grabPoint.position - grabPoint.position;
float angleAdjustment = Vector3.Angle(root.forward, gripsDirection); // Angle needed to bring it straight0
Vector3 relativeUp = Vector3.Cross(handsDirection, Hand.right);
Vector3 targetDir = Quaternion.AngleAxis(angleAdjustment, -Vector3.Cross(root.forward, gripsDirection)) * handsDirection;
targetRotation = Quaternion.LookRotation(targetDir, relativeUp);```
(targetRotation * Quaternion.Inverse(grabPoint.rotation)).ToAngleAxis(out float angle, out Vector3 axis);
rb.angularVelocity = angle * Mathf.Deg2Rad * axis.normalized / Time.deltaTime;```
Do you know quaternions well?
just enough to use them in unity
this is however too much math for me this morning lol
Me too
Forget the big math. Just this causes the issue too
Vector3 handsDirection = other.Hand.position - Hand.position;
targetRotation = Quaternion.LookRotation(handsDirection , Vector3.up);
why not normalize the direction?
idk I normally do it for direction. Idk if matters here prob nont
It looks like when the rotation goes to a certain point, it tries to do 360 degrees the other way
Debug values, make sure its not going to 0 vector
Are there issues when invoking events from async functions?
because for the last two days i've had various issues with events just not being invoked correctly
the only thing i can think of is that maybe its because im invoking from inside async stuff
should not be issue. are you sure that part of the code is reached
Hello, im having an issue that is giving me a headache, my game runs without errors or warnings iside editor, but once I make a build to test a few things, this is what I see when opening the game. Music is playing but as you can see the main menu aint loading and IDK what might be causing it.
Using default render pipeline and a very light project
and the target platform of the build is?
Windows
ok, so make a Development build and then look at the Player log
im coding stairs in my game,
for now just going down stairs
essentially if the space between my player and the ground is within a threshold, the player isnt already grounded, and the player isnt trying to jump,
then the player teleports down the distance,
the one issue with this is that the player will always teleport the last little bit at the bottom of a fall,
how do i fix this?
Unsure where this goes, but, if I wanna make a Play of the Game system like Overwatch in my game (where after a match, a recording of the best moment in the game plays for all players from the PoV of that player), would the easiest way to do it is to just record an actual video from the PoV of the player and keep it in a buffer or some other way, such as a "demo" like overwatch itself does it
Already tried to solve it yesterday, someone also told me that but i see nothing wrong or idk what am i exactly looking forhttps://hastebin.com/share/yahotojewe.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
thats what i would do,
the alternative is saving the exact animations and positions of every relevant object or player,
which seems like a nightmare and also will likely take up more space than a temporary video file
no, YOU look at the player log and look for errors
You could record a demo, which, seeing as it's a thing in a lot of popular games, works well and doesn't take up too much space? Gonna have to see how to even make one though
given you choose to make it so it saves a temporary video to play at the end of the game,
you could also very easily make a clipping system
Ye but i see nothing wrong thats part of the issue, no error logs
Everything seems fine
then maybe you should add some, no one but you can say what your game should or should not be doing
Like, putting a Debug.Log() everywhere ?
But whats the point if it works OK inside Editor
like putting them where you think it could be going wrong and narrowing it down from there
shoulnd it be some config in project settings or smth?
that is what we call debugging
Ikr, but there is literally no place where ir could be failing, I tried removing every scene but the main menu one, which is a simple image with play and quit buttons, and it still fails
you do realize that that statement makes absolutely no sense whatsoever
'it can not be going wrong' but 'it is going wrong'
Make a new project and try building it
again, what im saying is that it has to be a settings/editor issue since the scene has literally nothing, like 2 buttons and 0 code and it still fails
Dont project settings get stored inside the project folder?
Unity asset store apparently has quite a few replay systems to use, some of them even free, which is very handy :)
oh great is broken too
Then it's either your unity install or your pc, I suppose
Bruh I just opened another project and it runs
What is going on
Is it a different version of unity
Its different from the original one but the same as this
this one also works and is the same as the original
no that is not what you do
in unity, how can I make the navmesh agent not pick the shortest path to a destination point? Right now its kinda hugging along the wall until it gets to the point
https://gameprogrammingpatterns.com/command.html
Use the command pattern with all actions in your game, to make a replay you replay the events that lead up to the moment (or save the state at the beginning)
This is the same pattern that is used to make things like "undo" and "redo" functions in applications
To put it simply, you're storing the parameters of a method in an object and then storing that object
so instead of
Move(Vector3 vector, float speed) etc
it'd be more like
Move(MoveCommand command)
obviously, this will require a lot of refactoring if you haven't built your game up to the point to be able to implement this pattern
Well, my game doesn't exist yet, and I'll look into this solution if all else fails, such as using a Recorder from the Asset Store, do you think I could just do that? (Assuming it works for a multiplayer game, which it should..?)
well for a multiplayer game you're going to end up using the command pattern anyway for RPCs
or at least you should
also im not sure about the legality of a play of the game system, i believe blizzard has it patented
I still don't exactly understand what a command pattern is and what it does, isn't it a bit strange to create an object just for a method? If I'm understanding this correctly
Is it just the name or the literal Highlights feature?..
patents are based on how something works
so if your system works too similarly it could infringe (im not a lawyer though and this is not legal advice)
hey guys, i'm interested in behavior trees and i plan to use them for an ecological simulation. What i'm curious about is, will each entity have an instance of the BT?
Let's say i have 50 foxes, will each fox tick its own bt or is there a better way to do it?
ECS
Entity-component systems
Instead of each entity controlling its own behavior, there is one instance that controls all of them - the entities only hold data
at least thats my understanding
you create that object so that you can store the object in an array
so you can then recall those commands
Oh, so you can store functions/actions in an array, that makes sense
how can i implement complex behavior with ecs systems
Each entity will need to have a lot of parameters (parameters that you'd already have with per-entity behavior)
Wait, so does that mean you literally record what action every player does and then replay it? That's sick
Yes, its how those demos that play on the title screen of some games work
they quite literally just replay inputs
Is that how Demos in like, valve games or overwatch work
I dont know how overwatch works but source games have a recording/replay system i believe
Also is this in any way useful other than just making recordings of games
where you can replay exactly a player's actions from the console
Well think about how bad for performance constantly recording a video of the game will be
Then think about how you're going to get that video to everyone else
True, but having to factor your code in a specific way just for a highlights feature sounds a bit excessive to me
for a game like content warning this is a feasible idea because its such a small scale
command pattern is useful for designer tools as well, like imagine when you do ctrl+z when you want to revert in photoshop/aseprite or whatever
Although I suppose you wouldn't need that much factoring?
the only refactoring you need to do is changing the parameters to be an object
which i think can be automated
That gives me an idea to implement this into gameplay by having a character reverse time with their ultimate xd
i mean tracer wouldnt work without commands
Oh true
well i guess they could just be storing her position 3 seconds ago but idk
yea you could just pop the last few frames command from the array and everything would revert back to let's say 2 sec ago
not only does that allow for highlights, but you can have a full replay system
Nono, when you use tracer E, from your PoV you literally traverse on the same path you traversed, it's 100% commands
where you can watch every single thing that happens
for league of legends, i think it uses the commands to literally play the game again if you watch your saved game
yeah i guess so but that could also just be storing the positions of 3 2 1 seconds ago
True, true
then interpolating - but i doubt that
from what ive seen while playing tracer it replays very tiny movements
Does this mean that quite a lot of games actually use commands?
its one of the fundamental programming patterns so yes
again, read this https://gameprogrammingpatterns.com/command.html
whenever you can rebind your game controls it means command pattern is being used
Thank u for telling me :)
that's a wonderful book
it is a very good book and its completely free
I'll give it a read, thank u
is this your first multiplayer game
Second try, first try at a multiplayer game ended up with me making a Lobby system way after I made a lot of the game, created many game-breaking bugs that I did not have the knowledge to fix so I gave up
I'm working on making some streamlining tools for lobby relay + lobby
I'm probably gonna be using photon for this project, do you think I could use any of your tools or anything?
my tools are made specifically for unity services
i'd also recommend against photon from my own experience + their pricing
Surely the free version is enough for a small-scale multiplayer shooter?
Are there any better multiplayer solutions for unity
the free tier is for development only
Does that mean I can't release games using it?..
I'll need to look into that then damn, surely this only applies to paid games?
i'd recommend using either Mirror or Unity Netcode
swear im not being paid to shill unity services
i wish i was i'd love to be paid for anything i do -v-
how would i get the collision data like shown here?
https://youtu.be/ILVUc_yV24g?si=q-JPxuCLjPPnLUge&t=486
Letโs talk about stairs, why they suck in games, and what can be done about that.
You wouldnโt think stairs are that hard for video games, until you see some of the bugs they can cause
Check out a live demo of the OpenKCC Project here - https://nickmaltbie.com/OpenKCC/
Chapters:
00:00 Getting High
01:18 What are Stairs?
02:33 Hiding the Problem...
Mirror sounds nice, has docs and doesn't intimidate me
Mirror looks nice but I tried to get it to work with relay and it did not like relay
Might work with NAT punchthrough, haven't tried
Relay connects players to eachother through a relay, one of the players is a host players and the others are clients
It doesn't require port-forwarding
NAT punchthrough is basically a hacky way to get around port forwarding
sometimes works sometimes doesnt, depends on the network
you may see in some games they talk about your "NAT type"
So NAT punchthrough/Relay is what does the connecting and something like Mirror is what makes your code work? I'm sorry I'm pretty new to this
something like Mirror handles the netcode
so how the game works
Relay is the transport layer, which is what gets the connection going basically
Ye exactly, makes sense
i've taken a class on networking and got a CISCO certification and i still get intimidated by all the words
I think that relay would be the "Transport" and "Session" layer here
and Mirror handles presentation and you handle the application
this probably is no longer related to code though
well more related to #archived-networking
When did you try it? I found a unity discussion page where a unity staff says they didn't add Mirror support yet, and in around December 2023 they added it
True xd
When i started on my streamlining project
So about 2 weeks ago
Oh damn
Mirror support is iffy
you have to download a random package off of github then take some files out of it, then you have to modify those files because they don't compile, and blah blah blah
the solution they give to connect relay to mirror just straight up didn't work for me when i tried it
so i gave up and used relay and unity netcode* which are in the same ecosystem
Would you recommend I use that then?
whats your networking budget
#โ๏ธโphysics might be able to help?
Zero, I guess
This is not a large project I plan to release on Steam or anything, just really wanna make a game for friends and others
relay + unet would be best then
Wonderful, thank u
DM me if you need help with it because this is a monster i've been dealing with for the last half month
I'd love to save anybody the time from wrestling with trying to get this stuff to work
Thank you a LOT
I'll start working on the project in a few days :3
terrible practice but I used python flask for it once
its really easy to recreate whatever photon does with python flask
but youre using what's supposed to be a rest api to make multiplayer which is bad, terrible
was a fun learning experience but theres a lot of Websocket packages for c#
The transport part maybe, but these networking solutions are doing a bit more than just passing packets around, especially the newer Photon ones.
I have a bit of a problem with my AI system.
currently, my system has two components per npc, SensesComponent that's tasking with surveying the world and deciding which NPCs can be seen by this NPC, and AiBrain component, which is tasked with making all the decisions.
I think I remember hearing that classes are always get passed around as instances instead of copies, so I decided to let SensesComponent to store seen NPCs in a List of such class called AITargetObjectReference. It contains reference to the npc object, a couple of other variables, and a variable called freshness that gets increased by the SenseComponent when the NPC is in sight and decreases when it is not - I decided to emulate inertia of senses that way (AI doesn't forget enemy the second it turns around the corner, nor does it notice it instantly when it appears).
now the problem is that when I pass the result of the sensing to AiBrain component - the list contents apparently gets passed as a copy, not as an instance:
// in SensesComponent.cs
[SerializeField][ReadOnly] internal List<AITargetObjectReference> potentialTargets = new();
...
internal List<AITargetObjectReference> GetSensingResults() => potentialTargets;
It's being received in the Brain component thusly:
//in AiBrain.cs
private void ObtainTargets()
{
if (_sense == null) return;
List<AITargetObjectReference> localactors = _sense.GetSensingResults();
listOfEnemies.Clear();
listOfFears.Clear();
foreach (AITargetObjectReference target in localactors)
{
...
And the issue I noticed is that targets that are in the AiBrain do not update their freshness, meaning they remain as "seen" indefinitely.
How can this be remedied?
idk most of my work with Photon is just using RPC and Photon View
im pretty sure List has its reference passed rather than a copy. but if push comes to shove you can always use ref, something like
private void ObtainTargets(ref List<AITargetObjectReference);
from there you can call ObtainTargets(GetSensingResults()). doubt this would work though since this is an internal list
Should I make it public then, maybe?
Is AITargetObjectReference a struct?
No, it's a class
I do remember that structs are always get passed around as copies
Yeah that's strange. List is class, so it's definitely passed by reference already... Hmm
Could you elaborate on the list items' freshness values changing? Everything you've shared is synchronous, and the list is only stored in a local variable within AiBrain.ObtainTargets() - so I don't quite understand how items in the referenced list could be changing values at a time which would impact ObtainTargets()
Sure, it's handled in the SensesComponent :
foreach (AITargetObjectReference actor in nearbyActors)
{
... // calculations of bools are omitted
if (inRange && !ignore && inFOV && inLOS)
{
if (!potentialTargets.ContainsObject(actor))
{
if (actor.pawnType != EAiTargetType.Player)
{
//general case, notice object after a set amount of time has passed
if (actor.CheckAndIncreaseFreshness(awarenessIncreaseRate))
{
recentlySpottedTargets.Remove(actor);
potentialTargets.Add(actor);
}
}
else
{
//case for player, awareness acuteness varies according to difficulty
if (actor.CheckAndIncreaseFreshness(awarenessIncreaseRate * difficultySpike))
{
recentlySpottedTargets.Remove(actor);
potentialTargets.Add(actor);
}
}
}
}
else
{
if (potentialTargets.ContainsObject(actor))
{
if (actor.CheckAndReduceFreshness(awarenessDescreaseRate))
{
recentlySpottedTargets.Remove(actor);
potentialTargets.Remove(actor);
}
}
}
}
The CheckAndReduceFreshness and CheckAndIncreaseFreshness methods modify the freshness of the object in the list (and return a bool).
Unrelated to the question, but please make use of guard clauses to reduce nesting.
Some of the nesting is indeed probably unnecessary, but I leave it in as it makes the code more readable for me.
Are you aware of guard clauses? Instead of:
if (potentialTargets.ContainsObject(actor))
{
if (actor.CheckAndReduceFreshness(awarenessDescreaseRate))
{
recentlySpottedTargets.Remove(actor);
potentialTargets.Remove(actor);
}
}
You could rewrite it into:
if (!potentialTargets.ContainsObject(actor))
continue;
if (!actor.CheckAndReduceFreshness(awarenessDescreaseRate))
continue;
recentlySpottedTargets.Remove(actor);
potentialTargets.Remove(actor);
Okay cool ๐
I guess I'm mostly just wondering about the sequencing of these methods. Like ObtainTargets() will always grab a fresh reference to list, and then (presumably) operate upon it immediately and discard the reference. Even if a list was a value type, I don't see how ObtainTargets() could ever be retrieving outdated data. And unless there's some sort of asynchronous code or jobs involved here somewhere, it's not like the items in the list would be changing during a single invocation of ObtainTargets()... You could even verify that it's the same list at any point within ObtainTargets() via a reference equality check - _sense.potentialTargets == localactors.
Where in AiBrain/ObtainTargets() are you expecting to see different values? Is ObtainTargets() invoked regularly? Short of asynchronous shenanigans, the only thing I can think of is ObtainTargets() just not running again after the freshness values have been updated
ObtainTargets is runned from the Update() (though I thinking about moving it into Invoke, since it is probably a bit excessive to update targets every frame)
The discrepancy I see is that the AiBrain and SensesComponent run pretty much independantly from each other (the only time Senses call Brain is either when it detects HeardSound event, or decides that something has bumped into the NPC), the AI Brain calls ObtainTargets, and after that decides which target in the list it needs to held as a priority - so the list gets sorted by a variable in the object, and the top result gets assigned to a variable currentAttentionTarget. And when it gets to the said variable - it isn't updating anymore.
Hm... maybe it's the sort function that turns reference list into a copy of a list?
listOfEnemies.Sort((x, y) => x.importance.CompareTo(y.importance));
listOfFears.Sort((x, y) => x.importance.CompareTo(y.importance));
Those lists are separate variables in the AiBrain, that have contents added to them from localActors prior to sorting code.
Such a puzzle ๐
That arrangement for AiBrain/SensesComponent sounds fine to me ๐
Lists will sort within the same reference - so the act of sorting shouldn't result in a new list...
localactors doesn't get modified within ObtainTargets()'s
foreach (AITargetObjectReference target in localactors)
{
...
does it?
Sorry I brought this up yesterday but I still haven't been able to solve it T_T the white cube is supposed to follow my mouse in the computer but for some reason it's at a weird offset. Does anyone know what could be causing it? This damn thing has taken like 6 hours and I've made no progress.
No, the foreach just tests the target and then either skips it, or tosses it into list of fears or list of enemies.
how can i make my screen move side to side whenver the player is walking?
i just need a general idea
Would you mind posting the AIBrain code on like https://gdl.space/?
Sure, but it's almost 2000 lines... Gimme a sec
You can just make the camera game object a child of the player. Doesn't require any fancy code.
its a child of the player, but i dont think u understood what i meant
whenever the player is moving i want the camera to go left and right if that makes sense
thank you
Dang. Looked like it doubleposted so I deleted one and it deleted both.
I had suggested moving the camera. Looks like you saw it haha
i only saw one it may have been a glitch for you, but still thank you
Why can't I see my OnPointerClick function in my Event Trigger -> Pointer Click -> Function?
using UnityEngine;
using UnityEngine.EventSystems;
public class BuildingClickHandler : MonoBehaviour, IPointerClickHandler
{
public delegate void BuildingClicked(BuildingClickHandler building);
public static event BuildingClicked OnBuildingClicked;
public void OnPointerClick(PointerEventData eventData)
{
if (OnBuildingClicked != null)
{
OnBuildingClicked(this);
}
}
public string buildingName;
}
Changing the PointerEventData to BaseData works
When having a class, derived from the Editor class, do I have to wrap it with the UNITY_EDITOR conditional, or does Unity ignore it in the build automatically?
usually you would put it in an Editor folder so Unity ignores the whole folder https://docs.unity3d.com/Manual/SpecialFolders.html
i have a script that loops and instantiates an Enemy gameobject of type grenade. What would be the best way to keep track of grenade1, grenade2 and so forth?
an array/list? this probably begins in #๐ปโcode-beginner unless you mean something different
When not willing to put it there, do I wrap it?
Why does Unity struggle to find any input when I use KeyCode
It always throws up the error about the keycode not being found, but the name is always blank when I type the correct keycode in the controls list s
Dont use strings
what do I use instead
ah alright
was wondering because strings worked fine before I wanted to use keycodes
yes, but not like that
Also is KeypadEnter the same as the regular enter key? I dont see a non-keypad variant so not sure
it couldn't exclude it by default because you can put multiple classes into one file, and you have to include the UnityEditor namespace to use the Editor base class, which would break compilation. You would have to wrap it like you showed above, yes. Also, you could always use an assembly definition (asmdef) to control which code gets compiled to editor / runtime, but if you don't like separating things by folders then I will assume that is a no-go too
nvm
im working on an rpg and I'm running into some idea conflicts when working on the player character. The different components of the player (PlayerSkills, PlayerInventory, PlayerStats, etc) usually need access to each other, but manually dragging in each component to another isn't going to scale well. How should I handle this? My first thought is a Player component that just contains references to the components, but feels a bit dirty. Should I just GetComponent whatever I need?
Do you know whether putting it inside of the UnityEditor namespace also ignores in build?
Or do I still have to use the conditional?
I just don't like that my folder structure is going to collapse when putting all editor scripts into the Editor folder
I mean if you want you could put them all into one script, although that would make calling the individual classes a bit more tedious
You usually use Singletons for your Manager classes, but those don't seem to be ones
It's good to plan around using assembly definitions to organize (which requires separate folders for editor and runtime code) since it speeds up compilation times but also, to answer your question, yes you still have to use the conditional
For stats Ive just been using scriptable objects
Thinking about it abstractly is not gonna help. Take a few real life cases where one of the components needs to access the other one and try to find an underlying pattern that you can use to refactor the setup.
Got it, thanks a lot!
If you need help brainstorming that, share some of these cases with us.
Oh fuck me theres no more errors and the game crashes
This is gonna be a fun night
PlayerSkills is going to need access to PlayerStats to check skill requirements. Your Strength stat (in PlayerStats) sets the max carry weight for PlayerInventory . the specific skills are TBD atm, but I imagine there could easily be one that increases carry weight. Whenever you level you get a point that can either raise a stat or buy a skill, so whatever does the leveling up needs access to both PlayerStats and PlayerSkills.
I see. I wouldn't make these 3 components, but just plain C# classes, and just have them all accessible via the actual component(Character or something). Then each of them can access the other one via the character reference.
Is there a way of checking whether the code is running in a Test Assembly? I would think something like
#if UNITY_EDIT_TEST #endif
Would exist, but I can't find anything like it online / in the official docs. Of course #if UNITY_EDITOR works, but I want the code to run when I play in the editor as well.
what do you mean by a Test Assembly? A development build?
A separate assembly for Edit Tests
so something like this?
there you have your define, UNITY_INCLUDE_TESTS
I tried that one, but then even in Play Mode the code gets skipped.
My code atm:
#if !UNITY_INCLUDE_TESTS GameState.party.AddAlly(this); #endif
It does work as intended when I make a build
your other option is to add your own define constraint into both Tests and normal Playmode
Hmmm just including a !UNITY_INCLUDE_TESTS constraint in my scripts assembly doesn't work, I'll look around for some tutorials on the issue
Yeah, except make them properties instead of public fields, and maybe pass the character reference via a constructor or initializer method.
Hey can someone help me optimise my game
i get randomly 6k batches when looking in a certain area
also, why properties instead of public fields? to make the set private?
thats one reason yes, encapsulation. u can also do logic in the getter/setter if needed
true
actually, that's where I can call the ctors lmao.
public Inventory {
get {
if (_inventory == null) {
_inventory = new CharacterInventory(this);
}
return _inventory
}
}
id still initialize them in some method, which would give you a better order of defining things and you wouldnt need to null check everytime something wants the inventory. But doesnt really matter
also looks like youre missing the type there
Mostly to hide the possibility of modifying fields from other scripts. But it also makes editing easier for the future. E.g. you can run some kind of OnChange method to a property, which would be executed every time the variable changes, or add some validation (like _health = Mathf.Clamp (value, 0, _maxHealth)). Without property, you would need to copy-paste the code in every place you modify this variable. But probably in 80-99% cases fields will be more than enough.
what does FixedUpdate do when my game only runs at 45fps? Does it run 45x/sec? Does it change FixedDeltaTime?
https://docs.unity3d.com/ScriptReference/MonoBehaviour.FixedUpdate.html
This page explains it better than I can. Short answer, it depends on the frequency of your physics system. The default is 50x per second (or once every 0.02 seconds), and changing your FPS shouldn't interfere with that.
You can look it up at Project Settings > Time > Fixed Timestep
Hi i need assistance in an issue ๐
I'm creating an object in runtime via ProBuilder Plugin. unfortunately, it doesn't assign the values as it should be. how to fix that?
vertices nor faces are being assigned that i can use later on for extrusion
Are you sure that's how it's supposed to be used? Are you confirming with the docs?
https://docs.unity3d.com/Packages/com.unity.probuilder@4.0/api/UnityEngine.ProBuilder.html
yeah i believe so based on this documentary
Can you share the whole !code correctly? It's not quite clear where you create the mesh and where you try to access it.
๐ Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I've List of vectors 3d preprocessing that would define this polygon as it's positions. while faces are inserted as triangles that processing within the function CreatePolygon in a class Polygon . via ProBuilderMesh component i added them there and created the object by assigning values.
i debugged the code and the do really assign to positions and faces variables of the component. yet, i get withdraw them back from component after processing the mesh
Also, you can presume that activeGameObject is corretly stored in singleton class
Debugging of a simple 4 vertices example
What if you break with the debugger in CreatePolygon at the very end and inspect the proBuilderMesh variable?
I think you're just accessing the wrong object
ProBuilderMesh.Create() creates a new gameObject along with the component. Yet you return a different gameobject.
https://docs.unity3d.com/Packages/com.unity.probuilder@6.0/api/UnityEngine.ProBuilder.ProBuilderMesh.html#UnityEngine_ProBuilder_ProBuilderMesh_Create
well it still has the necessary values but upon GameObject return variable it assigns back to Null
Yeah, read my previous message.
That's a different gameobject
Not the one that you assign the vertices and faces to
Hey, could someone help me with the scrollbar issue I'm getting? I'm changing the content size dynamically through script, and I want the scrollbar to change its size accordingly to the newly changed content size, yet it stays the same size
For reference my initial content size is like 5 pixels wide, and when it expands horizontally,I can scroll everything just fine, yet the scrollbar stays at the size as if the content size is still 5 pixels wide
After updating to Unity 2022 from Unity 2019, I now am getting errors in one of my scripts (which was found online and edited) that I used to determine the material the character stands on, to play appropriate footstep sound.
Now it gets this error on meshes:
Not allowed to access triangles/indices on mesh 'Wood_beam_thick_256' (isReadable is false; Read/Write must be enabled in import settings)
Is it possible to get the required data without enabling write on all the meshes in the game, as it sounds a bit unpredictably dangerous for the assets?
The code that generates the error:
https://gdl.space/adisonofex.cs
You can toggle that per asset
If you don't want to do operations on source files, use .mesh instead of .sharedMesh.
https://docs.unity3d.com/ScriptReference/MeshFilter.html
This code looks really inefficient, you could just use GetIndexStart to see if tri is part of your submesh
Yeah but I'll need to toggle it for every asset which player could get on
Perhaps, I woudn't know, I didn't wrote like 95% of it
Would this work?
int triangleIdx = hit.triangleIndex;
int subMeshesNr = m.subMeshCount;
for (int i = 0; i < subMeshesNr; i++)
{
int tr = (int)m.GetIndexStart(i);
if (tr <= triangleIdx)
{
materialIndex = i-1;
break;
}
if (materialIndex != -1) break;
}
Hm wait no it wouldn't, I think...
This looks more like it
You'd want to see if triangleIdx * 3 is between m.GetIndexStart(i) and m.GetIndexStart(i) + m.GetIndexCount(i)
If so your material is i-th
Oh, thanks!
Basically this, right?
if (triangleIdx * 3 > m.GetIndexStart(i) &&
triangleIdx * 3 < m.GetIndexStart(i) + m.GetIndexCount(i))
{
materialIndex = i;
break;
}
Alright. I've got a Dissolve Shader Graph that I've set up, and a float property that controls the amount the Shader actually runs on the given object. It's supposed to trigger ingame when you press the spacebar, but it isn't proccing, so I'm not really sure what's going on there.
public class DissolverScript : MonoBehaviour
{
public float dissolveDuration = 2;
public float dissolveStrength;
public void StartDissolver()
{
StartCoroutine(dissolver());
}
public IEnumerator dissolver()
{
float elapsedTime = 0;
Material dissolveMaterial = GetComponent<Renderer>().material;
while (elapsedTime < dissolveDuration)
{
elapsedTime += Time.deltaTime;
dissolveStrength = Mathf.Lerp(0, 1, elapsedTime / dissolveDuration);
dissolveMaterial.SetFloat("_DissolveStrength", dissolveStrength);
yield return null;
}
}
private void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
StartDissolver();
}
}
}```
I just tried a Debug.Log on the last if statement to see if it was even getting the input, and it isn't, so I'm not sure what I'm missing, but that's probably it.
Just don't know how to fix it.
Take the log out of the if statement so it's ran unconditionally in Update. If you're still not getting it, then your script isn't active, it's on an object that is disabled, or is not attached at all to an object in the scene
Double-check the name of the material param, ShaderGraph is often very finnicky with it.
I'd also added a check that dissolve coroutine isn't already running, or else you'll get several competing coroutines
I think might have what I did wrong, depending on my understanding of the stuff. My material is specifically named DissolveMaterial, do I need to put that somewhere in:
Material dissolveMaterial = GetComponent<Renderer>().material;```
Since I was following a tutorial, so I might have just put what they called theirs.
Hey guys, i am using unity cloud save
and i am trying to make the player to change his name (playerName)
i want to make a function that check if there is any other player with the name he is trying to change ( CheckAvailability(string name) )
Anyone know how to query in cloud save?
QueryAsync seems to take two arguments, but you're only providing one.
yes, but i can't find any other example with the other param
Try things, can you construct an empty options with new QueryOptions()? Or maybe it has static members, like QueryOptions.Default? Use VS's completion list at your advantage here
guys, how can i fix this? looks weird ๐
This example is out of date, the technical documentation has two params : https://docs.unity3d.com/Packages/com.unity.services.cloudsave@3.2/api/Unity.Services.CloudSave.Internal.IPlayerDataService.html#Unity_Services_CloudSave_Internal_IPlayerDataService_QueryAsync_Unity_Services_CloudSave_Models_Query_Unity_Services_CloudSave_Models_Data_Player_QueryOptions_
But there is no example public?
start should be inclusive and start+count should be exclusive, like any other spans
No, they haven't updated it yet. As I said try things out, the worst that can happen is that you'll get an exception thrown
Ye i am trying but it is like 1 out 100 possibilities to hit the correct usage ahah
but thnks anyways s2
ill keep trying ! ๐ซก
I don't think I attached it. Do I need to put it on the given gameObject I'm using the material in quesiton on?
Yes of course, if you'd like Update to run, you need to attach it to an active object. It's the same as other scripts
Yep, got it working now! Thank you.
Mmm I love unchecked parameters leading to "low-level" HTTP errors from the web server
Try passing null as the options? I've seen some examples online where they also use new QueryOptions() but with no apparent issues (or the forum thread don't mention them)
It's a shame that these docs are not kept up to date lol
How to check if a specific component (InputSystemUIInputModule) is loaded somewhere in the game? Using RequireComponent is local to the game object only and of course ended up getting spammed with "multiple event systems present". I'd like to make this check once in the primary active scene manager, but would like it being able to check other scenes (event system would typically be present on a DDOL object, but if I'm running the scene in isolation, I'd want to create it myself as part of debug (will surround whatever logic with #if UNITY_EDITOR)
you could use FindObjectByType
That checks everything?
var uiInputComponent = FindFirstObjectByType<InputSystemUIInputModule>();
if (uiInputComponent == null)
{
}
oop, it's actually FindAnyObjectByType or FindFirstObjectByType not just FindObjectByType, but yes. it will check all actively loaded objects https://docs.unity3d.com/ScriptReference/Object.FindAnyObjectByType.html
That's perfect "This function is faster than Object.FindFirstObjectOfType if you don't need a specific object instance"
And I would just AddComponent if null, then?
yep
๐
and since UnityEngine.Object has an implicit cast to null, you can just do if(!FindAnyObjectByType<whatever>()) AddComponent<whatever>(); instead of splitting the lines up if you don't need to actually access any of the stuff on the component
I have a Vector2 member that i set in my component's Update() called transformVelocity, and I print the value of that out to debug log... Now when I access that same member in my OnTriggerStay2D function it ends up being 0 instead of the value reported in the Update()... is there something about OnTriggerStay2D that would cause this?
here is the code in the Update()
and in the OnTriggerStay2D:
use a bin site to share the whole class ๐ !code
๐ Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
and are you certain that these logs are coming from the same object? it's also pretty odd that you have exactly one log from update between each log from OnTriggerStay
it isn't always exactly one, i guess it just happened to be there for that clip
i mean usually it is, in the case that i'm looking at though
yeah i'm certain it's logs from the same object
how have you confirmed that
that doesn't mean the OnTriggerStay log is coming from that one
there is only one object that has an overlap as well
include the name and instance id in your logs to be sure
ok
yeah, same thing
my screenshot utility just broke
but i put InstanceID in log and it shows it's the same instance for both prints
ah wait, you only log the velocity when it does move. you need to log when it doesn't move too so you can see that it ends up at 0 before the OnTriggerStay tick
the thing is inside OnTriggerStay, the velocity is never non-zero
but i will try logging this all anyway
well you also never see when the velocity becomes zero between those physics updates
(transformVelocity.sqrMagnitude > 0.1f)
Debug.Log("tff:" + transformVelocity.sqrMagnitude);
You're only logging when it's greater than 0
if you only ever specifically log it when it is non-zero you won't see when it is actually zero
where in this several hundred lines do you actually move the object
Because the object is only moving in FixedUpdate
If it's a Rigidbody
it is RB
Yeah so
Stop doing physics stuff in Update
That's your lesson for the day
Velocity needs to be measured in FixedUpdate
For that matter why not just grab it from the Rigidbody itself
ohh
i tried grabbing velocity from the RB and it's just 0, probably because position is set manually most of the time
i mean position is set based on input
there, finally working. thanks all
Isn't there any way to solve this?
World up type None?
what should I do
The world up you actually want
Can someone help me solve a problem in my code? Itโs a 2D movement code and there is something I canโt figure out how to do.
Yes, pick the one you want to be "up" for the aim constraint
I have a movement code that works well, but when I move left and right the sprite flips according to which direction. My sprite is a hook that hooks onto things so I donโt want it to flip. Can someone please help me?
Actually, I tried them all, none of them changed the result, still the character's body becomes strange when turning.
whatever you are doing to flip it, just don't do that
I used this code when I started. So itโs copied from an old YouTube video, I have just been pasting it into my projects I need it in, so I have no idea what to do.
and since you've not shared any code i have no idea what you need to change either
Should I send a picture of it?
!code
๐ Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
What to do is learn how to code, learn how the code you're using works, or resign yourself to eternal confusion
Can I just send a pic of the code so I can know the part I need to fix?
No, read the instructions on how to share code that have been shared with you
I only have discord on my phone, so I donโt have the script on my phone itโs on my computer
discord is also a website
but even if we wanted to see pictures of the code, photographing your screen with your phone is an awful way to get those pictures
Screen shots
just post the code correctly
if it is short, yes
How much is considered short?
Just to check, does the * operator perform a dot multiplication?
in what context
well, I'm trying to outputVector.x * currentSpeed a speed
where currentSpeed is some positive float
that's just multiplying two floats.
"hmm" gets blocked; good job
yes because it contributes nothing to the discussion
It's outputting a positive number even if I move left; some debugging confirmed as much
I can use those sites. Iโm on my phone and it wonโt let me save it
log both values involved in the multiplication
why can you not just paste it to a bin site from your computer then just share the link from your phone?
So I'm suspecting I'm inadvertently absolute-ing them
well the multiplication operator is not doing that
I put the code into the site, and pressed the save button. Now what?
share the link . . .
did bro just manually type a link
my guy, you have a method that you call "Flip". if you don't want the sprite to flip then consider just . . . not using that method
I donโt know how to get rid of it. I tried and then the whole script didnโt work
how about you go actually learn what you are doing instead of blindly copying tutorial code without making an attempt to understand what it does
I'm an idiot for not checking that lol
oh ffs I'm adding the vector to the currentSpeed
So both have the same damn sign, so ofc their product is always non-negative
Can someone who isnโt a lonely person living in their parents basement help me out?
ah yes, instead of making an effort to learn what you are doing, let's skip right to ad hominem. fuck off.
baited
Can someone tell me how to get rid of the flip variable
there is no flip variable
...Find where you're flipping the sprite in the code, and then... remove it
It's not a difficult thing, if you know why you wrote the code that you did
sorry to um acktaully you but
there is a flip variable
that's not in their code
i even already told them exactly what they need to do. but allegedly it makes the whole script stop working (it can't)
I get an error and I canโt run the game
Well, if they're saying they copied code - which it feels like they didn't properly understand - then it's part of the script that causes the flip
Sounds like someone copy pasted code without learning the basics
that sounds like too much effort for them
insert creepypasta of choice here
- something something soul not found .exe
I got it. I deleted the whole bottom part last time instead of just the โflip();โ
Silly me!
what
what
they deleted the Flip method without actually removing the call to that method from their Update method. now that they've actually followed my instructions by removing that method call it works as intended
You should truly go over c# basics, there are many sites like Microsoft's learn site. You arent gonna struggle your way through a game not knowing the language or how to read a basic error
And plus if you're gonna try insulting people who helped u, u likely arent gonna get future help in here
So gotta learn the basics either way
Guys, im still looking for this, anyone know how to use QueryAsync here? i only want to select from my Unity Cloud Save where playerName equals the newName im setting to the current player. to check for name availability.
the error message is pretty clear, you have not supplied the second parameter that the method expects
Yes i know, but in the docs is not showing any other example with the second parameter, i am trying to implement the QueryOptions but i dont know how to
did you look at the docs for that QueryOptions type?
then ask in the #archived-unity-gaming-services channel if you don't know how to use that service
Oh, awesome thanks i will for sure !
how could i make doors work for a top down game
i got this so far a top layer for the walls of the house and a bottom layer for ground
but how could i make doors, cant do it on the tilemap right?
need a more specific question
like just generally how would i add doors to a top down game
look at how other top down games implement doors
thanks a lot
if you want to use a tilemap, you could have a door layer which has no collision
Anyone able to help with the following question? I'm trying to obtain a method using reflection but that method was sealed somewhere in inheritance. The method obviously still gets called on the base class and I need to invoke the method and have it make calls to deriving methods further down the inheritance line. Is it possible to do such a thing and if so, how would I do it?
i'm attempting to make a model importer, and I have most of it completed. however, i'm having some difficulties processing the armature information. i'm unsure how I should generate bindposes
this is my skeleton generation code
If it's sealed there's no such thing as a deriving method for it
I probably explained issue wrong, one moment while I write it up more coherently
I have a method DrawPropertyGUI() which I seal in a class. The class calls a lower down method DrawPropertyGUIWithEvents() which is designed to be the base functionality of DrawPropertyGUI() of the from that point forward. The base class simply calls the overridable method for its functionality along with some housekeeping for the base class. I need to invoke the base functionality of DrawPropertyGUI() externally via reflection and invoke it to draw properties and do housekeeping tasks
Why via reflection? Also, if DrawPropertyGUI is sealed.... then you simply cannot
I'm making a generic class selector and want to implement the drawing of custom property drawers inside of the class selector
Right now I invoke the DrawPropertyGUI() method from the custom property drawer in order to do this.
I could be missing something obvious. Any ideas?
The class calls a lower down method DrawPropertyGUIWithEvents()
What does "lower down" mean here precisely?
I need to invoke the base functionality of DrawPropertyGUI() externally via reflection
If it's sealed that should be very simple. Find the method with refleciton and call it. It cannot be overridden so it cannot be changed.
Not sure what the issue exactly is
are you saying you want to call DrawPropertyGUI without calling DrawPropertyGUIWithEvents()?
If so, that's beyond the limits of what reflection in C# can do for you. it cannot rewrite already written functions.
If you want that to happen, you need to separate the functionality you want into a separate method that doesn't call DrawPropertyGUIWithEvents(), and call that directly.
Lower down meaning in a deriving class
well it's presumably defined as a virtual or abstract method in the same class
so it's not actually calling a derived version, it's calling the virtual or abstract method, which gets resolved only at runtime
anyway it's beside the point
Right, because it's just overridden. My bad! So how would I go about executing this via reflection if that's even possible?
executing what
Can you answer this?
Is this what you want?
For example, you have something like this:
abstract void DrawPropertyGUIWithEvents();
sealed void DrawPropertyGUI() {
DoSomething();
DrawPropertyGUIWithEvents();
}``` and you want to do only `DoSomething();` and not `DrawPropertyGUIWithEvents();`?
I want to execute the DrawPropertyGUI for the base class
again, what does that mean?
Because DrawPropertyGUI for the base class includes calling DrawPropertyGUIWithEvents() as far as I understand
please correct me if I'm wrong there
See my example just above for what I think you mean
object customDrawerInstance = Activator.CreateInstance(customPropertyDrawerForType);
FieldInfo fieldInfo = property.GetFieldInfoAndStaticType(out Type t);
customPropertyDrawerForType.GetField("m_FieldInfo", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).SetValue(customDrawerInstance, fieldInfo);
objectPropertiesContainer.Add((VisualElement)customPropertyDrawerForType.GetMethod("CreatePropertyGUI").Invoke(customDrawerInstance, new object[] { property }));
So here's whats happening right now
that's not an explanation of what's happening right now
This is your code right now, which will very successfully call CreatePropertyGUI
in which case, you have achieved your goal
So I'm trying to understand how your goal differs from just calling CreatePropertyGUI
(you said DrawPropertyGUI above and this code says CreatePropertyGUI so i'm not sure which is right now)
I feel like I asked some pretty simple questions above
If you answer them, it will clear up a lot.
correct
ok so... again, your intention is to try to only call part of that function?
there is no "base function"
it's sealed
there's only one function
you said it was sealed
therefore there are no derived functions
this is exactly what I'm doing
right so then what you want is not possible
What you need to do instead is just call DoSomething(); via reflection. Not DrawPropertyGUI()
(per my example)
I could, but the issue with that is that I wouldn't know the name of the function I'm trying to call if I want to make this generically function for all property drawers
If you are making it "generically function for all property drawers" how could you possibly know what their CreatePropertyGUI functions contain?
Maybe you could back up and explain what you're actually trying to achieve here
It will always contain instruction to draw the UI toolkit GUI
you're asking an XY problem
indeed, but this CreatePropertyGUIWithEvents function is something you created so, it's really unclear what you're asking still
you're asking some very specific question about your attempted solution which for some reason involves reflection
but you haven't explained what you're actually trying to do
The following code attempts to draw the properties in the inspector for a selected type via a dropdown. I currently take in info for an attribute, find all deriving types via reflection in a dropdown menu and let the user select one. Once the user selects a class, I want the drawer to display the drawer found for the type inside the property drawer. If one doesn't exist, it just defaults to drawing all the field for the type
this is why my code is heavily utilizing reflection
hey guys, how can i make an object lock to the cursor? i wanna make a flashlight stick to the cursor the whole time
i have a custom cursor as well currently and a cursor manager and this is the code i have:
`void Start()
{
cursorHotspot = new Vector2(cursorTexture.width / 2, cursorTexture.height / 2);
Cursor.SetCursor(cursorTexture, cursorHotspot, CursorMode.Auto);
flash.transform.position =
}`
i dont really understand what this error is even saying
what does it mean 'extra field'
there's only one
Sound like you're using conditional compilation and one of the fields is not compiled in the editor.
that cant be right, its probably an editor glitch
!code
๐ Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
there's no compilation errors, only build errors
Can you share the code of LobbyList as well?
Also, do you have some assemblies that are only compiled for the target platform?
ah no it was just an editor bug
i restarted and it decides my code is fine now 
i tried forcing a recompile too and that didn't work
is it me or does Physics2D.Raycast function only work if you pass in a single layer mask, it doesnt work with combined layermasks?
is that to be expected ?
It should work. Make sure you're using the correct overload of the method.
i'm passing in an int in both cases so i don't think its the wrong overload
So in the commented out case it doesn't hit anything at all?
well it doesnt hit Stage, thats for sure
Then debug what it does hit.
Perhaps there's an object on the bomb layer that is hit first.
it doesnt hit anything as of now, i just never checked it against Bomb
right
And when you uncomment it and log what the raycast hits, what does it show?
the commented code makes it miss all hits with Stage
A raycast would only hit the first thing in it's way.
If there is an object on the Bomb layer in front, it would only hit that.
Yea. RaycastAll.
Look at the docs for physics2d. Itll list all the methods
Hello,
I'm currently working on the implementation of the new Input System and I wondered if it was possible to wait for an input in a coroutine?
Here's the code
protected IEnumerator WriteText(string input, Text textHolder, Color textColor, Font textFont, float delay, AudioClip sound, float delayBetweenLine)
{
textHolder.color = textColor;
textHolder.font = textFont;
StartCoroutine(MakeSkippable());
for (int i = 0; i < input.Length; i++)
{
textHolder.text += input[i];
if (input[i].ToString() != " ")
{
SoundManager.Instance.PlaySound(sound, "Sound");
}
yield return new WaitForSeconds(delay);
}
yield return new WaitUntil(() => OnSkipDialogue());
Finished = true;
}
The errors:
- CS1662 Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
- CS0029 Cannot implicitly convert type 'void' to 'bool'
Could you help me please?
The OnSkipDialogue function is called when the player presses Enter (keyboard) or Cancel (controller)
Did you look at the docs for WaitUntil, you need something that returns a bool
You could just store a bool and set it to true in OnSkipDialogue
I have an system where players can pick up dropped weapons by pressing F. But when the player picks it up, the weapon doesn't go to the hands transform but rather above their head. The weapon is still a child of the hands transform upon pickup. The hands transform works indicated by the rocket launcher. The pistol and the knife doesn't apply
Here's all the code associated:
https://hastebin.com/share/ihubihihal.csharp
Anyone have any decent tutorials/advice on async/task stuff? I have a saving animation and I want the data to save asyncronously so it doesnt interrupt the animation, not sure where to start. Found some forums but nothing really useable. Thanks! (never touched this stuff before now, this seems like a simple enough problem to get started on)
edit: also I do already have a save/load system I just want to make it async somehow or write a method that asyncly calls my existing save function and waits for it to be done
You can use a coroutine to make it async as well.
I can? Currently I am yielding until the save is done and then continuing but it interrupts the animation
Or just some checks in update
What kind of animation? Is the animation related to code?
no it is a play on awake function that just moves something across the screen
no code attached
"play on awake function"? So it is a code driven animation?
and my save coroutine is literally just this (as pseudocode):
yield waituntil save
yield return startcoroutine(fade screen function)
load next scene
Well, That is "async" technically.
no like play on awake is checked I meant so when the scene loads the animation plays until the end of it
If your save is taking a lot of time and is executed on the main thread, there would be a stall obviously
that stall is unavoidable?
It is avoidable. But async is not gonna help with it. At least not the way it's normally used in unity.
hmm okay what would you suggest?
Use the profiler to see if it's actually a stall
okay one sec
how would I be able to tell if its a stall?
for some reason the times are missing but
its 260ms but im missing details?
can u not expand that to show more?
Is that the spike selected?
yes
for some reason details are missing on the main window
Scroll the hierarchy view to the right.
you can also make the column smaller by dragging the while line near Total to the left
Is that a third party library or something?
what do you mean? the SaveGame ?
yeah one sec
thats the name of my class so
its not an instruction
yield return new WaitUntil(SaveSystem.SaveData);
thats probably the line its worried about
just encrypts and saves the data
the encrypting is what is taking a while ill save you that effort
I can send it if youd like though
Send it.
But if what you're saying is correct, then it's this encryption that you'll need to async or on a background thread.
static string Encrypt(string plaintext, string password)
{
byte[] salt = Encoding.UTF8.GetBytes(password);
byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
byte[] key = GenerateKey(password, salt);
byte[] iv = GenerateIV(password, salt);
using (Aes encryptor = Aes.Create())
{
encryptor.Key = key;
encryptor.IV = iv;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(plaintextBytes, 0, plaintextBytes.Length);
}
return Convert.ToBase64String(ms.ToArray());
}
}
}
If it's many small operations, you can make it async on the main thread.
If it's one big operation, there's not much you can do aside from running it on a background thread.
ahhh
so should I make my save function async then so that I can await the encryption
is that like a standard approach
Share the SaveSystem.SaveData code
public static bool SaveData()
{
try
{
FileStream stream;
if (File.Exists(path))
{
stream = new(path, FileMode.Open);
}
else
{
stream = new(path, FileMode.Create);
}
BinaryWriter writer = new BinaryWriter(stream);
PlayerData data = new();
string textData = JsonUtility.ToJson(data);
string pk2 = $"{GetCode1()}-{GetCode2()}";
string encryptedData = Encrypt(textData, pk2);
writer.Write(encryptedData);
writer.Dispose();
}
catch (Exception)
{
return false;
}
return true;
}
Might want to place some profiler markers here to make sure we understand correctly what causes the spike.
ah okay i have not used these before
static readonly ProfilerMarker s_PreparePerfMarker = new ProfilerMarker("SaveSystem.Save");
public static bool SaveData()
{
try
{
s_PreparePerfMarker.Begin();
FileStream stream;
if (File.Exists(path))
{
stream = new(path, FileMode.Open);
}
else
{
stream = new(path, FileMode.Create);
}
BinaryWriter writer = new BinaryWriter(stream);
PlayerData data = new();
string textData = JsonUtility.ToJson(data);
string pk2 = $"{GetProcessorID()}-{GetMotherboardSerialNumber()}";
string encryptedData = Encrypt(textData, pk2);
writer.Write(encryptedData);
writer.Dispose();
s_PreparePerfMarker.End();
}
catch (Exception)
{
return false;
}
return true;
}
am I way off
I think one of the main issues here is that you're executing the whole save logic on the yield instruction. That's definitely gonna botcher unities coroutine execution quite a bit. You should just be checking a simple bool instead. Something like: SaveSystem.SaveComplete.
The profiler marker needs to be inside the method.
Aah
Okay, that's fine.
And place another one in encrypt
and then just set that bool at beginning and end of save?
Yes.
is that not the same effect as waiting for the save to finish
or you are saying that yielding the method is screwing the coroutine
is there a reason also you're converting to json, encrypting, then writing as binary? because binary isnt human readable anyways
No, since you're waiting for the whole logic to complete. Even if the logic itself was async(on a background thread), you'll end up waiting for it in the main thread.
but its easily convertible
If it was a simple bool check, unity would check for it real quick and continue executing it's player loop. While currently it has to wait for it.
ah ok so ur saying async wait for the logic and set the bool when its done
So is your existing method, as anyone will have access to this code
I say that wait until should just be checking for a single bool. Not executing a whole method with separate logic. At this point, there's no point in the wait until at all, as it would always return try anyway.
What do you mean by this 2nd sentence
Yeah, and I bet that big part of it is the GC.
The entire SaveData method is executed synchronously.
Putting it in a coroutine doesn't magically make something asynchronous.
Wait until is called by unity every frame to see if the coroutine can be resumed. If it returns true, it resumes the coroutine, otherwise checks again on the next frame.
What you have now is that it executes the save method entirely instead of checking a variable. This would mean that unity can't move on to executing other code until the save method returns.
Obviously that's only part of the problem, but it's still something you should consider refactoring.
ok I'll turn that into a bool now, and then should there also be internal async methods in the save system
I'd start from getting rid of the GC overhead.
You can create the arrays and other data structures on game start in your SaveGame class. Then reuse these arrays instead of creating and destroying new ones on each save.
I'd truly just get rid of the encryption and move on if it works as fast as you want. Though not sure how much of a "encryption wont matter locally" talk I wanna go through
its a static class ๐ข
Doesn't really change anything.
if they get the password they deserve it lol
You can have a static constructor or some kind of initialization function where you do that
oh yeah...
Idk if JsonUtility or your PlayerData is thread safe or not, but you can just do that part on the main thread and move everything else to a different thread and that will be all.
Don't need to change much else.
Same could be said about anyone who actually decides to convert from binary to json, and then back. Trust me when I say if the password is local then they already have it. Itll just be a minor headache for the person who writes an app to modify save files if your game gets popular enough
yeah but i would rather it be a mediocre headache than a minor one, binary is way too easy I would rather encode and encrypt
If it's a single player game, who cares if the player is cheating; if it's a multiplayer game, you can't protect it this way regardless.
That would probably be a simpler solution, but I wonder if it's actually not as slow as we think and the main issue is garbage collector.
I doubt GC kicks in in that exact profiler frame to be the issue.
Not sure how saving is used in their game, but usually allocation is only a big concern in reoccurring operations, so things that are called every frame or every fixed amount of time, if GC can't keep up with your allocation then it has no choice but to pause the world to do clean up. In one off operations, allocation is generally fine, and presumably saving isn't performed all the time.
ok I improved it, visibly less buffer, still a tiny kick though
static string _password = null;
static byte[] key = null;
static byte[] iv = null;
static byte[] salt = null;
static void Init()
{
_password = $"{Code()}-{Code1()}";
salt = Encoding.UTF8.GetBytes(_password);
key = GenerateKey(_password, salt);
iv = GenerateIV(_password, salt);
}
this is whats left of the save function:
public static bool SaveData()
{
try
{
SaveComplete = false;
FileStream stream;
if (File.Exists(path))
{
stream = new(path, FileMode.Open);
}
else
{
stream = new(path, FileMode.Create);
}
BinaryWriter writer = new BinaryWriter(stream);
PlayerData data = new();
string textData = JsonUtility.ToJson(data);
string encryptedData = Encrypt(textData);
writer.Write(encryptedData);
writer.Dispose();
SaveComplete = true;
}
catch (Exception)
{
return false;
}
return true;
}
SaveSystem.Init();
SaveSystem.SaveData();
yield return new WaitUntil(() => SaveSystem.SaveComplete);
not sure if this is what you meant?
this would still run all at once, when you call SaveData
how do you mean
all your logic is still running on the main thread, when you call a method it will run to completion
using System.Collections.Generic;
using UnityEngine;
public class LinkedComponent : MonoBehaviour
{
[SerializeField] private string comment;
[SerializeField] Component linkedComponent;
[HideInInspector] public Component link
{
set => linkedComponent = value;
get => linkedComponent is LinkedComponent ? linkedComponent.link : linkedComponent;
}
}```
compilation error: ```'Component' does not contain a definition for 'link' and no accessible extension method 'link' accepting a first argument of type 'Component' could be found (are you missing a using directive or an assembly reference?)```
how would I get link to return linkedcomponents link if the linked component is a linked component?
(i hope that made sense)
i could obviously just getcomponent, but if there's multiple how do i ensure that its the correct one?
ah I need to make it async? I am not very familiar with making/using other threads
Hey, Im trying to add ads to my UWP unity game. I came across this provider called AdsJumbo. But they seem to have only native cpp support. So how do I call methods like ShowInterstitial and ShowReward from within the unity C# script to the external native code?
you could look into multithreading but its not something id truly recommend if u arent good with it already
:/ is that the only option or would using a Coroutine work here
looks like u just need to do this
if (linkedComponent is LinkedComponent linked)
then you can access it
I'd say that 6MB of GC is quite a lot. As for the GC timing, we don't know for sure. It might be happening right on the spot.
Profile it again.
coroutines run on the main thread, so no it wouldnt work. Multithreading is your only option if you want multithreading
thanks, did not know you could do that before
Why is it called during the save..?
Putting the entire encryption process on a background thread would be rather easy. I do not think that the encryption algo itself is parallizable.
Why does your init generate 6mb of garbage ?
Well, from what we can see, the save itself, including the encryption is just 3 ms. The issues was the GC.
it does seem like a lot, especially since encryption is made to be quick. It could also be from that _password thing which is 2 method calls and string interpolation
Yeah, Code() and Code1() are sus as well.
moving the init nulled it out or at least like 95% of it but I can't notice it and the editorloop takes longer than the save now so thats a win
sus but not performance intensive
Thank you @cosmic rain and @lean sail for the help appreciate it seriously +1 rep for you both


