#archived-code-general
1 messages · Page 268 of 1
I saw this before, but wasn't entirely certain how I was supposed to use it
"Note that IgnoreCollision is not persitent. This means ignore collision state will not be stored in the editor when saving a scene."
Serialize the colliders to the root script and run that method in start it seems
Hello, how can i prevent microphone streamed audioclip to capture ingame sounds?
I have the problem that my platforms disappear behind the background and I haven't been able to get it fixed for 2 hours. Does anyone have any further ideas?
That's not enough info to go off, but did you try changing it's z position and/or sorting layer/order in layer?
yeah i tried not working
Then you'll need to share more info
What information do you need?
What does it look like? What is it obstructed by. What components and setup does that obstructing object have.
Also, I didn't realize it, but this is a coding channel and your issue doesn't sound related to coding
guys i am working on a capibara runner game, where obstacles (different prefabs i made with specific heights from the floor). There are no syntax errors in my code, and everything should be alright in the inspector. The obstacles DO spawn randomly (succesfully), HOWEVER, 5 of the 6 are invisible? Honestly no clue why, pls helpp
asked chatgpt it just told me to reimport the png assets and recreate the prefabs (doubt this will do anything)
Is there a way to set up a UI Toolkit Button's clicked value in the UXML editor? or only programmatically?
querying in code with selectors to set callbacks feels like jquery 🙂
is that a question addressed to my enquiry? or just your own haha
- Pretty sure your IDE is not configured.
- You misspelled Start
- You're probably not spawning them in view of the camera
All of the prefabs are spawned from the same spawner, they are all in frame 100% as the basket obstacle is clearly visible when spawned, and others although arent visible, still stop the game if hit
All you have to do is pause the game and look at the scene
And just look where they are
My own 🙂
I'm trying to implement drag and drop with UI Toolkit and it is proving... difficult
oh you are right, such a dumb mistake haha
the prefabs are actually there! but they are behind the background image for some reason. Changing their z axis coords in the inspector doesnt do anything. Do you think i should bring the background way back then?
also my bad i just needed to update my visual studio editor within Unity for my IDE to be fully configured again
in what way ?
Can't find where I can listen to drag events, for one. all I can find is button.clickable.clicked
Ah, registercallback maybe
all good now guys, thanks for help

probably on the visual element
Thanks yeah, I was completely overlooking what I needed. Thanks
Alright. Anybody still up? For renderTexture raycast issues, is this the correct place or do I have to go "UI-UX"?
I'm trying to raycast a crosshair over an image to the world, without inputs. I have the position of the crosshair on top of the RenderTexture and I want it to raycast straight forward.
However this is the best I could figure, it's going down and only works when the crosshair is at dead center
Can you show the math you're doing to calculate the ray/line?
Can I link you to the Forum post? I have a lot more info there. Is it OK if I link it here?
does anyone have any idea what I'm doing wrong here. I'm trying to make a idle animation loop on between each other bit my counter is counting to fast or at least perframe. Does anyone know how to fix this
{
string[] idleAnimations = { "idle", "idleStart" };
AnimatorStateInfo stateInfo = animator.GetCurrentAnimatorStateInfo(0);
if (stateInfo.IsName(idleAnimations[0]))
{
if (stateInfo.normalizedTime >= 1f)
{
loopCount++;
if (loopCount >= maxLoopCount)
{
animator.Play(idleAnimations[1]);
loopCount = 0;
}
}
print(loopCount);
}
}
}```
You should just be using a StateMachineBehaviour
Hi everyone, I was wondering if someone could give me some ideas with why Unity would stop logging any logs on entering play mode. The TL;DR is that I have been given a project to look into and to get it to work I was going to log some of the values for a curtain script. These didn't seem to show up so I thought it wasn't calling it, anyway double checked with breakpoints and all seems well but that left the logging issue. Next I tried creating a empty monobehaviour with a custom editor and button which would just output "Test" on being clicked. This works fine when not playing, but the second I go into play mode no logs appear in the console. All selections (for logs, warnings and errors) are active. So this is 100% a play mode issue. I've never experienced anything like this and searching online or reading through the project settings doesn't come up with much.
This is a VR project so potentially that may have something to do with it? Maybe its forcing all logs to go to a headset that doesn't exist in this context. Or maybe there is something called through script that disables the console. Honeslty I'm completely lost so any help with getting this working again in play mode would be appreciated!
Look for Debug.unityLogger.logEnabled maybe someone was trying to be fancy and disable logs for release but forgot to wrap it in the proper defines
Hey guys! I've been pouring over the documentation to see if there's a simple way to reference a specific track or track group from a timeline asset. But rn it looks like if I wanna access a specific track/track group I need to know what index or uhh "place" it's at in an IEnumerable. And I guess I could always put the specific track I want to work with at the top but I want to be sure I don't accidentally reference a different track. So are there any recommendations on how I go about referencing a specific track?
Hello. I'm building two android apps from one project, I do change their package name, but I can't install them both on my phone, I'm getting an error: "android app not installed as package conflicts with an existing package".
Command "aapt dump badging "D:\path\to\project.apk" | findstr -i "package: name"" on apk files shows that package names are different, what else am I missing?
Problem was with custom "AndroidManifest" that our company used, I didn't know about that. After changing package name in this file everything worked.
I been trying that but i got no luck with it
i wanna save the players inventory asynchronously, is it better as a Task or Coroutine?
iirc Coroutines still sort run synchronously in a way right?
Coroutines run from a (active) MonoBehaviour on the main thread, yes, they just allow a function to yield instead of complete to end
coolio, thanks 🙂
looks like saving to playerprefs likes to only be done on the main thread, so going of what you said, coroutines look like the way to do it
async functions also run on the main thread unless you ask them not to, they're just not tied to the lifetime of a monobehaviour and can't do the unity-specific things like waiting for LateUpdate or end of the frame
Heya all, having a bit of difficulty with async here. Can someone explain why unity waits for run_async to complete all in one frame even tho its async? Thanks very much!
public Chunk(Vector3 offset, int lod, WorldRenderer renderer) {
data = new ChunkData(offset, lod);
run_async();
}
public async void run_async() {
Task vertex_task = calculateVertices();
Task triangle_task = calculateTriangles();
await vertex_task;
Task uv_task = calculateUv(); // Requires vertices
await triangle_task;
Task normals_task = calculateNormals(); // Requires vertices, triangles
await normals_task;
Task texture_task = calculateTextureV3(); // Requires vertices, triangles, normals, biomes
await uv_task;
await texture_task;
applyMesh();
loadStructureNoise();
loadStructures();
calculateGrassChunks();
}
anyone ever had issues with listview pushing other stuff in a container even when it's set to shrink 1 and the other stuff to 0?
basically this
this is equivilant to
void drawFrame(Canvas canvas) {
canvas.clear(CanvasKit.WHITE);
// code to update and draw the frame goes here
// make sure we run again
// so we keep animating
tr.RunOnMain(drawFrame);
}
tr.RunOnMain(drawFrame);
in which we must ensure a task queueing itself such as above will not end up running endlessly
eg the task gets dequeued and runs
sometime layer it finishes and queues itself again
at this point we may still be executing queued tasks, in which we will now see the thread that had requeued itself
this will result in executing it again in the same frame
in which case since we are running on the UI we will block until the task finishes at which point it is queued again thus we see it again, and again, and again, endlessly blocking to execute the same task
this is exactly what we MUST avoid doing
listview flex params vs header panel above vs the panel they're contained in vs the tab that panel is in https://i.imgur.com/iCM6Bcs.png https://i.imgur.com/AseRFZT.png https://i.imgur.com/Kn6BliX.png https://i.imgur.com/hNUIDn6.png
how are you measuring this? this should run across multiple frames, but it won't suspend until you hit an await so if calculateVertices and calculateTriangles do a lot of work up front you might still have a slow first frame
so you reckon just await them all
ended up making a selector for tab view header container to set shrink to 0. not entirely sure why anyone would want tab buttons to be able to shrink by default
well just making something async/return Task doesn't do much on its own, if you await an already completed task it just continues in the same frame, so it's up to you to break up the work across multiple frames
you can use await Task.Yield() which on the main thread is roughly equivalent to yield return null in a coroutine, or if you have stuff that's safe to run off the main thread, you can do that with await Task.Run(() => { ... })
you would probably need to multithread for that to have a boost tbh
the main point of async is to do things off the normal chain of events in the main thread
depends if your goal is speeding it up or just to keep the ui responsive during a long task! even if you're stuck on the main thread it can be worth splitting an expensive cpu task up
async makes it easier to break up a task across multiple frames, when there is a lot of work to be done, and you don’t need to do it all in one frame
exactly, using multithreading is just a bonus sometimes
i would not use async to multithread, these are like two different things
anything you do async should be thread-safe by default, tho
but not done with the intention of spliting threads
im simply trying to execute the chunk's loading calculations over a number of frames so that the entire thing doesn't freeze for the player. unfortunately i need to access some of unity's methods so not all of it can be async so scheduling it all appropriately isnt easy
it's totally fine to call unity methods from async methods, if you don't deliberately run stuff on another thread you will never leave the unity main thread
its not liking me initialising a new game object ect.
you should have a failsafe for if the player reaches a chunk not fully loaded yet, where you do pause the game until async loading is done
all in due time yes, first i need it to end up fast enough
people will always find a way, be it BLJ or bullet time boost, to go fast as fuck into unloaded areas
for now, just start by loading your chunk asynchronously
there's no reason that shouldn't work in the snippet you sent so maybe the problem is elsewhere?
i had this.chunk = new GameObject("chunk", typeof(MeshFilter), typeof(MeshRenderer), typeof(MeshCollider)); in applyMesh() but it didnt like it
where's this code being called from? eg what's in the stack trace from the error you get
UnityException: Internal_CreateGameObject can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
UnityEngine.GameObject..ctor (System.String name, System.Type[] components) (at <3b24cc7fa9794ed8ab04312c53e6dedd>:0)
Chunk.applyMesh () (at Assets/Scripts/World/Chunk.cs:375)
Chunk.<run_async>b__12_0 () (at Assets/Scripts/World/Chunk.cs:66)
System.Threading.Tasks.Task.InnerInvoke () (at <787acc3c9a4c471ba7d971300105af24>:0)
System.Threading.Tasks.Task.Execute () (at <787acc3c9a4c471ba7d971300105af24>:0)
--- End of stack trace from previous location where exception was thrown ---
Chunk.run_async () (at Assets/Scripts/World/Chunk.cs:66)
System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_0 (System.Object state) (at <787acc3c9a4c471ba7d971300105af24>:0)
UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () (at <3b24cc7fa9794ed8ab04312c53e6dedd>:0)
UnityEngine.UnitySynchronizationContext.Exec () (at <3b24cc7fa9794ed8ab04312c53e6dedd>:0)
UnityEngine.UnitySynchronizationContext.ExecuteTasks () (at <3b24cc7fa9794ed8ab04312c53e6dedd>:0)
so idk how im not on the main thread
are you calling the constructor of Chunk from the constructor of an asset or script?
Hello so i am having some trouble with an enemy i am programming for an vr game. When the enemy collides with anything it will attempt to walk into it and then start walking upwards. https://hatebin.com/mcrbekvvtm
scripts, its not mono. thats why i initialise a new game object, i mean i could have it as a scriptable object but even so
so it's in a scriptableobject constructor? those aren't called from the main thread either
shit. so im better off attaching the script to a gameobject with the necessary components and initialising it that way?
Hi all, has anyone had issues with reloading the current scene a player is in?
I have a scene that instantiates a lot of procedurally generated content and deletes some other content. When I use SceneManager.LoadSceneAsync I'm expecting the scene to revert to it's original state, but the content I generated or deleted previously does not reset.
it depends, you can use Awake on ScriptableObjects iirc, it's called the first time they're loaded, but yeah you're probably better off adding some code at the beginning of your game/level which calls an init function on those objects
alr cheers, ill switch it to a prefab and give that a shot 👍
yo there is some weird shit going on here, ive switched it but it still says its not on the main thread and i cannot think why other than the async function which i call on initialisation:
public async void run_async() {
await calculateVertices();
await calculateTriangles();
await calculateUv();
await calculateNormals();
await calculateTextureV3();
await Task.Run(() => applyMesh()); // Within this function
/*
loadStructureNoise();
loadStructures();
calculateGrassChunks();
*/
}```
`UnityException: get_mesh can only be called from the main thread.`
Task.Run is one of the ways to explicitly leave the main thread 😄
that runs the given delegate on a background worker
ples help
Actually I dont think i explained it properly because it is no longer walking towards the player when it is collided. this is when it starts to punch and it slowly starts rotating upwards
I'm working on AI that manages a base and I'd like to make the AI replicate a human player in ability. For example, moving to locations, placing expansion and production buildings, etc.
This is sort of like an RTS game AI, and I've been practicing on how to achieve this using some of Unity's build in systems
I was experimenting with ScriptableObjects for predefined builds, but I'm not sure they're the best approach
Anyone have experience with this? I was thinking a predefined Queue Manager that accepts Actions, but can have overrides for dynamic events in the game that aren't scripted
ScriptableObjects are good for storing blobs of data that can be referenced from multiple places
I was working on an RTS a while ago. I didn't have any pre-defined builds; I just had rules that searched for the best place to build something when a criteria was met
(the search is gradient-ascent based)
im working on a board game and i was wondering if anyone has any tips on how i can do movement on pieces between tiles
"movement on pieces between tiles"
wdym?
move the white square from its current position to the middle of any of the surrounding tiles
Ohh its pretty easy stuff , is this tilemap? you get helper methods on the Tilemap class and Grid
maybe you can use some a* as well
for walkable and unwalkable paths
no its different game objects since each of the colored tiles will have different stats attached to them
ScriptableTiles would've been the answer to that
and its different for every time i load it
they can contain data / custom functions
Like I said you might want to look into A* for pathing
i m making an inventory system and it says i can t conver string to int but it is a way too?https://pastebin.com/3BZmUjKb The error is at line 22
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.
why is this even in update lol
itemName is an int
not a string
public class Inventory{
public int itemId;
public int itemName;
}```
i know, but then why is this problem?
thanks
whats what a problem?
also this belongs in #💻┃code-beginner
Because it is an int
You're saying = "skill1" to an int
That makes no sense
Make it a string
is your IDE not showing that ?
no
you dont have this?
no
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
make sure you configure your code editor
For the new Logging package. Is there a way to attach a gameObject to the message like in the Debug.log so when you click on the message it selects the object in scene?
Does anyone know if there is a C# script for a 2d game, basically I want to create a mechanic, that after the knife cuts the bread (goes through all the bread collision) changes the sprite
What's a c# command?
script
You'd have to code whatever feature you're wanting.
I'm assuming the breakdown of the mechanic you're wanting is...
- Knife started cutting the bread: knife has entered the bread.
- Knife finish cutting the bread: knife has exited the bread.
- Consider evaluating if cut was valid
- Change some sprite(?)
You'd could use the rigid body callback functions for enter and exit.
How can i limit the shooting angle like in the picture, if your mouse is within the red zone, it would teleport to the closest possible allowed zone. This is the code so far for rotating the gun
It's really hard to answer this without understanding what exactly you mean by the mouse being in a zone. What kind of game is this? Does the image represent positions on the screen? Or something else?
the character itself is in a car, its a top down shooter type game, the red zones would be the car's front and back sides. at the moment i have the gun rotating around the gun in a fixed circle independent of how far away the mouse is.
And is this suppsoed to be relative to the rotation of the car?
yes, if the car is turned 45 degrees, the green zones should shift aswell
So I am assuming you want the gun to only shoot towards the closest point to the mouse *in the green zone*. I would probably get the angle of the center of the car to the mouse, and have logic based on that angle
aka
if mouse is in XGreenZone angles track XGun
else if mouse is in XRedZone angles and closest to XGreenZone Set XGun angle
okay, i have an idea of how to implement it now, cheers:D
You'll want to do all the math in local space of the car though
Yeah good point, will be easier
e.g. once you get a world direction vector, use car.transform.InverseTransformDirection(worldDirection) and do your math with that vector
Yo guys I want to ask for something. I am new at Unity and I was watching a basic game tutorial. But when the guy opens a new script it opens Visual Studio but for me it opens Visual Studio Code. Why does it do that because I think my code does not work properly in vscode
I want it to open Visual Code
But dont know how to do that
Configure whichever IDE you want to use
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
What do I do
it didnt fix anything I have a script called birdscript and it automatically sends me to vscode and I dont want that I want it to send me to visual studio but cant find how
it does, click on Visual Studio and follow the instructions for that
I did
If you set the external tools menu properly, it would take you to VS instead of VSCode
screenshot your External Tools page
Inb4 "what's external tools?"
Edit: called it
ok but how to go to the external tools menu (sorry i dont know anything abt unity)
so you lied
It's in the guide you said you clicked
External Tools is part of the steps. If you followed it as you said it would be familiar..
do you want to see the pack manager?
No
pack manager has 0 to do with what was requested
im a bit new to C#, are there any types i can use to do this more efficiently than a dictionary?
thats at the end..
Not just part
you skipped the whole beginning
ye im doing it now 1 m
I already googled this too but I couldnt find where "preferences" button was after clicking on "edit"
Edit in UNITY. Right? Not in Visual Studio
ye
Screenshot your edit tab
you mean the top left edit button right?
Yes
the one you clicked where you couldnt find preferences
I think I prefer the first
Yeah, definitely 1
wdym
why are you using lowercase/camel for classes and methods?
i think it looks better
well i started C# 3 days ago
keep that uglyness to JS
ive never used js in my life
do you write lowercase class names in lua?
never will either
no i used snake case
windows 11 I was doing smth Im sending a ss
LOL
then why the hell you use lower case in c# lol
i just think it looks better
no point of arguing over code style
sure, preference but still
i suppose i should learn conventions if i want a job
ofc
if you want to work with others yes you need to use common style
its piined in this channel
Is anything magic happening to AudioSources when they're played? I have an audiosource pool that reuses them. The pooled objects are created and DontDestroyOnLoad is called on them.
Now sometimes I get an error from my pooling code that I'm trying to access an AudioSource that was destroyed.
There's one instance where I parent the audiosource to play on a moving object. But I tried unparenting at the and of the clip playing, I also tried listing the AudioSources found in children in OnDestroy of the object I'm parenting at and looks like the audio source is already unparented when it's destroyed.
(it also looks like the unparented source comes back to the dontdestroyonload scene in the hierarhy after setting parent=null)
cant see a preferences button
why are you using OnDestroy if you have Pooling ?
@rigid island
why you cutt off the rest
should be literally under Project Settings..
I'm hooking a pooled audio source to a flying object, then after I do some async scene reloading my pool is suddenly missing an audio source
I just put ondestroy for debugging to test a theory that maybe the audio source was still parented when that object got destroyed
that doesnt answer the original question
yeah sounds like ur mixing stuff up
DDOL should not be used if you are pooling them
? the on destroy was on the object I temporarily hook my audiosource to play a clip on a moving object, I'm not destroying the audio sources
so why did you get error, that you are trying to acces a component, on a game object that was destroyed
we need to see context / script
Ok so, I have found the issue finally thank yall. It says visual studio code [1.86.1] for me (now) but I can change it to Visual Studio community 2022 [17.8.6] but in the site it says visual studio enterprise
thats because the screenshot was from microsoft website so ofc their version of VS is enterprise edition
oh ok so the community one I must select right?
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.
click regen project files after you do that to be sure
we need to see the exact error + show the stack trace
trying to reproduce, it's not happenning 100% of the time :/
when i try to make 2 scripts with ontriggerenter it gives error and i have no idea how to make it work with 1 script, am i understanding this wrong?
how the hell should we know without even seeing the error?
oh right mb:
You have accidentically duplicated your script
oh my god
ive spent the last 30 minutes redoing all my code so it fits naming conventions
i was already 3,000 lines deep when i learned there were naming conventions for c#
3,000 lines thats it?
i mean
i started c# and unity 3 days ago
and most of the time in that 3 days was practicing pixel art
i want on the start the game and the save file to load. i can t write (SaveDataObject, path) becuase "No overload for method 'LoadData' takes 2 arguments". And it dosen t know what to load.
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.
Finally my bird is floating 🙏
so im trying to make it so when u touch a object at scene 1 it sends you to scene 2 and at scene 4 when you touch a object it will send you to scene 1 and because i cant make 2 scripts of OnTriggerEnter i have no idea what to do.Is there a way to fix it?
first things
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
i am using visual studio
is there any reasons why a static class holding data could be ignored in a build ?
Yeah I have to let it go, I thought I maybe fixed it randomly but reverted all my changes I was hoping would fix it and I still can't reproduce it. I'll screenshot it when it comes back, but it was just an error from the pooling code that the audiosource referenced by the list is was missing 🤷
great so configure it according to the Visual Studio link
I know it's not very unity specific question, but I just want to make a sanity check for myself:
if I store some reference to a reference type object in a struct when passing this struct to a method - this struct will be stored and boxed automatically in a heap and not in a stack just because it contains reference type and will cause garbage collection after I'm done using it in a method, right? so I can never use struct with reference type value in it without garbage generation?
i got this, but the code isnt working in my build
public class CrossSceneDataHolder : MonoBehaviour
{
public static bool InstantStart = false;
public static bool StartInTuto = false;
}
// somwhere else
public void Restart()
{
CrossSceneDataHolder.InstantStart = true;
CrossSceneDataHolder.StartInTuto = _playerC.InTutoLevel;
SceneManager.LoadScene("Game");
Time.timeScale = 1;
}
I'm not technically sure, but did you put this CrossSceneDataHolder on any gameobject? Cause as far as I know - if you didn't put on any gameobject a script - unity will ignore this script in a build and cut it off, but I can be wrong about it
Also, maybe use scriptableobject for this task rather than mono?
i thought about that, but even when its added somewhere in the scene and loaded it doesnt work
hm, strange
Hi all. I need to load multiple scenes at once, instantiate objects in one scene, and use occlusion culling in another. I don't want to instantiate objects in the same scene that I'm using occlusion culling, but occlusion culling only works in the active scene. I don't want to have to remember to add a 'move to scene' script to every object I instantiate. Is there some way I can override the active occlusion culling asset?
I need to load multiple scenes at once, instantiate objects in one scene, and use occlusion culling in another.
This is my actual problem. I'm familiar with this page and linking to it isn't helpful
the gist of it would be explaining why you need to do that in the first place
- need to choose an 'environment scene' and use occlusion culling in it because the user can choose an environment
- need to instantiate dozens or hundreds of objects in another scene without them disappearing between environment changes because we don't want that to happen
- don't want to manually mark each object I instantiate with DontDestroyOnLoad because it is a hassle
I've been looking at a few verlet rope implementations and there's this recurring thing when adding gravity
someGravity * Time.deltaTime * Time.deltaTime
Why twice?
Depends on context but t^2 usually refers to acceleration.
What would be the advantage in doing this over using a vector of smaller magnitude for instance?
One would be relative to time while simply using a small value would be relative to frame.
I guess what I can't wrap my head around is if we multiply the vector by the delta, we're already relative to the frame. Multiplying it further seems to complicate things needlessly. Don't get me wrong, I am absolutely sure I am missing the point.
isnt Occlusion Culling something you bake prior to enter Playmode ?
The vector would be the speed relative to some direction. Multiplying it by time would make it a velocity. Further multiplying it would make it the acceleration. The purpose is likely to take steps relative to acceleration.
Character controller would be a good example of using acceleration rather than some fixed value.
Wherecs playerVelocity.y += gravityValue * Time.deltaTime; controller.Move(playerVelocity * Time.deltaTime);They'd acquire the player velocity of gravity by first taking the speed and multiplying it by time then once again to get the acceration for that frame.
@dusk apex
Ahhhhhh....
So say we have 1D with a scalar for velocity, a scalar for the gravity.
v += g * deltaTime for the force applied to the velocity for the ongoing frame
position += v * deltaTime again for the step
and since verlet does not maintain the velocities, then it makes sense to multiply it twice
this makes absolute sense, thank you so much @dusk apex
yes
then I dont understand this statement
use occlusion culling in it
what does this have to do with loading multiple scenes
Occlusion culling is only active in the active scene when multiple scenes are loaded
Then objects instantiate in that scene instead of the scene I want them to spawn in
How so?
Why don't you read the page you linked me? https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.SetActiveScene.html
The active Scene is the Scene which will be used as the target for new GameObjects instantiated by scripts and from what Scene the lighting settings are used.
so switch it after you spawned the objects you want ?
although the usecase still isnt clear why you're doing this
Objects can spawn at any time
then two scenes makes no sense to me
I need to spawn objects and keep them as the environment changes
And I need to use occlusion culling in the environment
many ways you can do this, triggers, raycasts..
so use DDOL
like I said, that is a hassle to have to do for every single object that I could spawn
if there is no way to do what I want and the answer is 'no' then that is fine. I simply wanted to know if there was a better way
it doesnt need to be done on every object, just the parent that holds them all
make a common gameObject / holder
use DDOL on that
I unfortunately need to keep objects at the scene root due to a networking library
idk then I would just put them inside a List of object that are set on DDOL
no clue how to help with your issue sorry
more of a general question, is there a advanced colider script for like buildings with holes (doors) and L shaped buildings? The box colider just boxes everything up, and the mesh colider dosent work with doors.
Hello, someone can help me?
I'm getting this error, but I don't know how to solve
I tried google, but don't works
FormatException: Input string was not in a correct format.
That's my code
int inGameItemID = int.Parse(EventSystem.current.currentSelectedGameObject.transform.GetChild(0).GetComponent<Text>().text);
I tried to show in a Debug.Log, and the result is always a number
I don't know where is the error :/
But the error are returning this line that I showed
holy mother of long ass function is going on here
what did you debug? show it
Image about the error and the line
where is the debugged value
I'll get again
A moment
Is it not Int32.Parse() ?
btw you should use TryParse
Im thinking it failing because its null
Test your C# code online with .NET Fiddle code editor.
Isn't null :/
show me what the code looks like
where is the string coming from
Here
your error from before showed the lines to be in the 135ish
this one printed from 235
are the not printing in the same function you attempt to Parse?
pretty sure EventSystem.current.currentSelectedGameObject.transform.GetChild(0)
is not grabbing what you think its grabbing
hmm i see. Maybe try storing it inside a variable and try that with print
I'm trying to store in a variable already
string text = EventSystem.current.currentSelectedGameObject.transform.GetChild(0).GetComponent<Text>().text
//Debug.log(text)
//parse text
what did Debug print tho
Wait
I remember this problem
this is caused by Text component adding some weird ass character to string
dont use that trash component Text its legacy anyway, simple fix
use TMP_Text with TextMeshPro - UI
I have code that triggers an (dash) impulse on a key press. It disables the primary moving scheme and I've confirmed none of that code is running while the dash is happening. But if I start the dash while moving, I go a lesser distance than if I start the dash from standstill. I've confirmed the impulse force should be the same in both cases.
Does anyone have an idea why this might be the case? Is there some relevant physics property or Rigidbody2d quirk I might be missing?
I'll try
I'm using a legacy text in ui
yes I know this, time to switch up.. that component gets pixelated and blurry on high rez anyway
you have to at very least provide !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.
I'm getting another error now
In the same line
Its spread across too many scripts to share easily. I tried to isolate it down to that particular Rigidbody2D.AddForce call that seems to be producing different results based on starting conditions.
But isn't null the value
show the code
of that line
you probably didnt change the type
yea just show the script /method related to AddForce
Is the same that before
Only changed Text > TextMeshProUGUI
hmm are you sure the child of currentSelectedObject has that component on the gameobject
Debug.Log(EventSystem.current.currentSelectedGameObject.transform.GetChild(0).name)
you should really store these in variables
Are stored
var eventObject = EventSystem.current.currentSelectedGameObject
var firstChildofSelected = eventObject.transform.GetChild(0)
var textObj = firstChildofSelected.GetComponent<TMP_Text>()
its not though
that long thing is hard to debug individually for a null ref debug
Which the difference? @.@
Will result the same error, will not? :/
print the string char by char with the int value (cast it to int)
the difference is you can debug better, its to find out who is the NULL object
if you dont learn how to debug you wont get far in code
Hm... Okay, I'll try
I'm trying, keep calm
Why are getting a null error?????????????
Isn't null
There are a value!!!
WHY ARE RETURNING NULL!!!!!!!!!!!
AAAAAAAAAAAAAAAAAAAAAAA
what is line 140
I want to die ;-;
hint: it isn't the string that is null
you have screenshot a Text component, this does not inherit from TMP_Text so that GetComponent<TMP_Text> returns null
I'll change
A moment
also note that it is possible that GetChild is returning null. you aren't doing any null checks on any of these objects and just expecting them to work
Indeed , having a script on ShopItem with those fields assigned would be smarter / robust
I told you why
Text component adds weird char to String
use textMeshpro
you tried to fix it by making it worse
I changed to TextMesh, but resulting the same error
look
var textObj = firstChildofSelected.GetComponent<TMP_Text>() did this before
you can Debug.Log all three
and see which one it is culprit
chances are you did not Put the textmeshpro component on that child
and its still Text
Is text mesh
these cutoff screenshots are worthless
i need to see the whole context
Where is this, which one are you trying to grab
etc
What I need to do, then?
Record my entire screen by 14 hours?
I'm trying to solve it since 10am yesterday, now is 00:20am here
have you tried screenshotting the whole object and the hirerchy clearly visible ? and point which object is calling this function?
would that be too much to ask?
or do you want me to guess
Also is doing this that complex to help debug ?
var eventObject = EventSystem.current.currentSelectedGameObject;
if(eventObject)
{
var firstChildofSelected = eventObject.transform.GetChild(0);
Debug.Log($"firstChild {firstChildofSelected}");
if (firstChildofSelected)
{
var textObj = firstChildofSelected.GetComponent<TMP_Text>();
Debug.Log($"text obj {textObj} ");
}
}```
edit: fixed NRE for Debugs
note that if any of those lines NRE then the log won't print
yeah this whole thing is flimsy and I would opt for a script that has those assigned and only do a TryGetComp
edited 🙂
Heya, I'm trying to have a line renderer bounce off the wall and it works except under certain conditions. When I point the line renderer in the right direction the next point in the linerenderer is set on (0,0) instead of bouncing normally and i have no idea why. Can anyone help me? Here's the code that does the line:
` private void OnTriggerStay2D(Collider2D other)
{
if(other.tag == "Projectile" && playerMovement.isSlowmo)
{
//start position
Vector2 startPosition = other.transform.position;
lr.SetPosition(0, other.transform.position);
//start 1straycast
RaycastHit2D hit = Physics2D.Raycast(startPosition, direction, 100, layerDedection);
lr.SetPosition(1, hit.point);
Vector2 bounceDirection = direction;
for(int i = 1; i < playerManager.amountOfLasers; i++) //playerManager.amountOfLasers
{
startPosition = hit.point;
bounceDirection = Vector2.Reflect(bounceDirection, hit.normal);
hit = Physics2D.Raycast(startPosition, bounceDirection, 100, layerDedection);
Debug.Log("startPosition: " + startPosition);
Debug.Log("bounceDirection: " + bounceDirection);
Debug.Log("hit.point: " + hit.point);
lr.SetPosition(i + 1, hit.point);
lr.positionCount = playerManager.amountOfLasers + 1;
}
}`
please use paste site to share large !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.
when exactly is the condition that breaks it you say?
i can barely even tell myself to be honest. here's a video, hopefully that makes it a little more clear. it's just that when i aim at certain directions, mostly around the x axis, the line renderer snaps to the origin. what's weird is that if i move the walls closer it doesnt happen
the original ray already looks off
why's that
oh yea true, nah that work is intended. the main character faces your cursor perfectly, but since the line is coming from the projectile they don't have to go over the cursor if the projectile is a little to the side
if that makes sense lol
the startposition and bouncedirection both seem to be good but hit isn't working for some reason. it has to be something in this line:
hit = Physics2D.Raycast(startPosition, bounceDirection, 100, layerDedection);
wait you're talking about the length ?
I think the issue might be the ray in the loop
yea i know it's the ray in the loop, that part of the code does the second laser
omg, i increased the length and it works now. i feel stupid, i didnt know length worked like that lmfao. thanks for the help
awesome! glad you got it working
How can I compare a mesh inside an asset vs a mesh inside a (loaded) scene?
//this prints Cube (UnityEngine.Mesh) : Cube Instance (UnityEngine.Mesh)
Debug.Log($"{assetMeshFilters[i].sharedMesh} : {sceneMeshFilters[c].sharedMesh}");
if(sceneMeshFilters[c].sharedMesh == assetMeshFilters[i].sharedMesh)
Debug.Log(assetMeshFilters[i].name);```
seems like the mesh inside scene is an instanced mesh (as expected), so the comparison always returns false
Man.. I wish git had an easy way to "amend unpushed but not last commit".
hmm. actually... git commit --fixup $SHA maybe? edit: yep indeed, if followed by a rebase .. squash it becomes a single commit
My script was looking messy, so I wanted to see how good a job CGPT could do, this is before: https://hastebin.com/share/yexuqahiqe.csharp. And this is after: https://hastebin.com/share/asapahobun.csharp. Somehow the after functions the exact same as the before, but its "cleaner."
It put some things into functions, added a load of redundant comments, and reduced some extremely basic logic
Thats why I put cleaner in quotes, because its not really cleaner, instead, every single little piece of the script is in its own function.
Hello, everyone. How can I lock the cursor so that it can only move arround one half of my screen??
There is a way to do that or is it impossible?
restrict the image of cursor / system call
Thank you, how can I do that?
by checking if the cursor position out of bound?
Ok 🙂
why intellisense not working visual studio code i updated VS in the package manager and VScode it selected in external tools
!ide Make sure you did everything in the guides
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
i did every thing but still the same
i don't have any suggestions beyond what is there
i didnt know these had names
And SCREAMING_SNAKE_CASE
what is difference between Material.proptype and materialpropertytype
https://docs.unity3d.com/ScriptReference/MaterialProperty.PropType.html
https://docs.unity3d.com/ScriptReference/MaterialPropertyType.html
is HideFlags.HideInHierarchy suppose to hide it in the scene view as well?
No
I got list of structs
if i do myList[someIndex].someVar = someValue will this update correctly ? Or do I have to save the value, change what i want, the reassign to the list index ?
yea
structs are moved around by value,
does it prevent OnDrawGizmos() from being called?
you can try passing the struct using the ref keyword
No idea, wouldn't be surprised if it did
sad
okay ty
if your using a list of strcuts, Im sure if u use the the index(for loop), you should be fine
if you use for each then no
private void FixedUpdate()
{
Vector2 up = transform.up;
hit = Physics2D.Raycast(transform.position, -up, suspensionDistance + radius, collisionLayers);
isGrounded = hit.collider != null;
Debug.DrawRay(transform.position, -transform.up * (hit.distance), Color.green, 0.0f, false);
}
Hello, i am trying physics2D out for some vehicle physics that only need to move forwards and backwards in a straight line
But the raycast doesn't seem to work, it doesn't draw the green line, i tested it with the maximum distance before and it does draw a line then but the raycast doesn't seem to hit the floor
do i need to change a setting on the collider maybe?
Your code isn't actually checking if the Raycast hit anything
Also your inspector is in debug mode
You also set the duration of the draw line to 0 seconds?
yeah 0 seconds means 1 frame
FixedUpdate doesn't run every frame
i tested it with a different ray before it works
just not sure why it doesn't give me the distance
Back to my first point
You might just not be hitting anything
Add an actual check and logs
i should be, because i should be casting downwards and there is a collider there
if (hit) {
}
else {
}```
Rule 1 of debugging is don't make assumptions
hit is a raycasthit2D
Actually test it
I'm aware
i am testing with the ray drawing
Test it with real code instead
Your ray isn't drawing. That strongly implies the Raycast isn't hitting anything. Add logs as suggested
Vector2 up = transform.up;
hit = Physics2D.Raycast(transform.position, -up, suspensionDistance + radius, collisionLayers);
isGrounded = hit.collider != null;
if (hit)
{
Debug.Log("hit");
}
else
{
Debug.Log("False");
}
Debug.DrawRay(transform.position, -transform.up * (hit.distance), Color.green, 0.0f, false);
Did it like you showed and i don't think you can use If (hit)
because it says i hit somethng
the Raycasthit2D is never null
This is correct
Now print what you're hitting
We're not checking for null. There's an implicit conversion to Bool. It's doing the right thing
The DrawRay needs to be inside the if statement as well
it's hitting itself, so in 2D physics raycasts can hit their own colliders?
like if it starts inside the collider
is there a setting to allow raycasts to start inside a collider without hitting it?
or do i need to make it a layer the collider does not hit
i found a setting: ```csharp
Physics2D.queriesStartInColliders = false;
now i can use it
The Raycast doesn't have a collider. Raycast is just a static function
Yeah, but i meant the collider of the object i am shooting my ray from like the ray starts in that collider
Sure but Raycast has no concept of that because it's a static function
There's no way for it to know
Hi. Does anyone know why do I keep getting the error "Action map must be contained in state" after I try to change something in the action map after loading the action map JSON please?
when i build the game and open it it shows a black screen is there a way to fix it?
What platform are you building to? What is your first scene (scene at index 0 in your Build Settings)? And does that scene have an active camera?
im building for pc and my first scene is main menu and it also has a active camera
_beeStock.ForEach(action);
Why is this guaranteed to run at least once, even though _beeStock.Count is 0?
private readonly List<Bee> _beeStock = new();
Is it?
public void ForEach(Action<Bee> action)
{
_beeStock.ForEach(action);
}
public void Render(Apiary apiary)
{
if (!CanBeRendered)
{
Debug.LogError("Is already active");
return;
}
_container.SetActive(true);
_amountText.text = apiary.Size + " / " + apiary.Capacity + " Bees";
apiary.ForEach(Instantiate(_beePanelPrefab, _scrollViewContent).Render);
}
This is how I use it anyway
It's not.
ForEach will run the method zero times on an empty list
Do you have any code that might be disabling or changing the active camera in some way for your "main menu" scene?
however, I don't think your code does what you think it does
Instantiate(_beePanelPrefab, _scrollViewContent).Render
This instantiates the prefab and then grabs its Render method
So your method would run the new bee's Render method once for each item in the list
You always instantiate exactly one bee.
Oh so the lamda is incorrect
checked the scripts, doesnt feel like there is any and also it works in the engine but when i build it and run it and the game opens its just black screen
Yes
apiary.ForEach(bee => Instantiate(_beePanelPrefab, _scrollViewContent).Render(bee)); fixed it, thank you!
oh right, the new bee panel, not the new bee
that makes a lot more sense now
i was wondering why the bee had a Render method that accepted a bee
Hmm, you could try making a "development build" to see if you get any errors when you launch, if you made a new scene with just a camera and maybe a light source, and had that new scene as your only scene in your build settings, does it also only give you a black screen in a build?
i did that and its a blue screen now
A blue screen is usually the default camera settings, so it sounds like in that scene your camera is working, you may have a setting on your camera in the conflicting scene thats not rendering, maybe a layer your camera is ignoring?
!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.
Hey guys, why isn't my while loop working? When Points == 0, it sometimes generates other difficulty then Basic, and nothing is printed
https://paste.ofcode.org/YMGnGzvhk4yCeTgMvgWuDa
how do you know that points is actually equal to zero?
because I have a TMP_Text in-game and when the player starts, it's at 0
also, what are you expecting to be printed?
like, when the difficulty was advanced but the CurrentDifficultyList does not contain advanced, because it now currently only needs to generate Basic levels
print("*Rerolling* Got " + MiniLevels[RandomInt].Difficulty);, I'm guessing?
Can I have help please
I am doing an Endless gamemode, which generates random mini levels, that has difficulties attached to them in inspector, and the stages are seperated into 3 categories, each point means one mini level done, the further the player gets, it should logically get harder, so more difficulties of levels are added into CurrentDifficultyList
Do you use rigidbody?
yep
I'd suggest logging the current Points value and the contents of the current difficulty list in NewLevel.
That will reveal exactly when NewLevel is running
oh f
I know where's the problem,
You see, in the (IsStarting) condition, I forgot to implement the same logic, because when it generates the first level, there is no check for other difficulty
Yes however if i did not no collisions would be detected
You can block rotation from the rigidbody component, if you don’t want the player to rotate upwards you should block the y rotation (I think)
k ill try that
could i get some assistances if anyone is available?
Otherwise you can put in code: rb.freezerotation = true
Which just prevents physics to affect rotation
Okay so essentially ive been tasked with recreating the "Simon" game and i have 4 functional buttons that play sounds based on input and whatnot but im trying to make it to where when i press the button it appends it's ID to a list so that i can check the list with the "supposed to be list"
but for some reason its not letting me reference another script's list to append the ID to
You need a reference to the script, but if you don’t want to reference it you can use a static List or a singleton pattern
tysm that worked @quaint reef
np
a list cannot really be a reference like a gameobject can
From what you're describing you do not need to store list in each individual button
Just store it in one single place or as lacitud suggested singleton pattern or static list
When you say "it's not letting me" what exact error are you getting. In the compiler, or while the game is running?
i'd do a function like
public void UI_AppendToList(int buttonIndex) {
list.Add(buttonIndex);
}
then add it to the button click event
sounds like the easiest way
It is the easiest and most scalable way
Its a compiler error
Tell us what the error says
is your IDE configured?
yeah it is
and i dont have the error since i deleted it to work on that solution
You can reproduce the error
It sounds like you're just trying to reference a private variable or something simple
well initially i was trying to inherit the other scripts into a single script which i understand why it didnt work
Regardless, the button solution is simple and would work fine.
Also you don't really need to save a list of all the inputs most likely. In Simon, you typically lose as soon as you press a wrong button, so you can just have something (a gamecontroller script or similar) check each input against the list of correct inputs. Each time there's a new input, you move to the next index in the list
Are we casually gonna ignore the fact you have created a script called "Monobehaviour"?
Ah, that would do it.
good catch
You've created your own MonoBehaviour class and it's completely blowing up everything else
How do i make it so the game ends in unity in my scripts
bool GameOver;
GameOver = true;

yea but that wont actually end the game
You have to manage gamestates for that
wdym and how
"ending the game" is a very abstract concept
actually nvm
if you just want to quit the game completely, that's what Application.Quit is for
i dont need help with that
Look up tutorials on YouTube for what you actually want to achieve
otherwise, ending the game just means...not running the game
maybe you go back to the title screen
i have a PlayerData script and i want to reference the coin variable to the player script but if i kill something it sohuld give me coin+= 4. But it remains 40;https://pastebin.com/XFRR9sfk
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.
Where are you "killing something"?
I don't see a function that does +=4 coins
thanks
Welcome??
i forgot to just write that, idk how
I'm too dumb to figure out the logic for this one:
_visualsSpriteRenderer.flipX = targetX < position.x;
Why is this wrong :(
i dunno, what's the problem?
In context:
var position = transform.position;
var targetX = Mathf.Clamp(
position.x + Random.Range(-3f, 3f),
CameraMovement.MAX_TOP_LEFT.x,
CameraMovement.MIN_BOTTOM_RIGHT.x
);
var targetY = Mathf.Clamp(
position.y + Random.Range(-3f, 3f),
CameraMovement.MIN_BOTTOM_RIGHT.y,
CameraMovement.MAX_TOP_LEFT.y
);
_visualsSpriteRenderer.flipX = targetX < position.x;
be more specific. because you haven't explained what you are expecting to happen compared to what is actually happening so we can really only make assumptions
It should flip the sprite if it moves left and not if it moves right
To sell the top down effect
What is the issue though? What is happening in the game that you do not want to happen?
Hi Guys, Is there anyone who is good with ML-Agent? I'm having some problems and I could use some help
#1202574086115557446 and https://dontasktoask.com
oh and don't crosspost. you've already posted your question in the correct place, keep it there
Very much so, I don't know why you would use the same name if you were going to derive from unityengine's Monobehaviour anyway
You can either A) change name of your class, or B) use UnityEngine.MonoBehaviour for inheritance
I would recommend A
naming a class MonoBehaviour is extremely foolish when using Unity
Also i see your script being named "MonoBehaviourScript" in folder but "MonoBehaviour" in class wassup with that 
Keep the name same in both places or you'll run into more errors
the name of the class should describe what it does
like PlayerMovement, or CameraController, or ImpactHandler
If I was making a custom extension to Monobehaviour, I would generally name it something like "CustomMonoBehaviour" or something, not like this
And inherit this wherever I want
Namespace is totally different thing
namespace is a part of the true class name
MonoBehaviour is a class in the namespace UnityEngine. the true name for this class is UnityEngine.MonoBehaviour
It's like a classroom and students
Where classroom is namespace and students are class
2 students from different classrooms can have same name and still be recognisable but not in the same classroom
If you define a namespace called MyGame.EnemyScripts, and put a class in it called EnemyMovement, then the true name is MyGame.EnemyScripts.EnemyMovement
how do i make it so the material of a new obj is the exact same as the old one? rn, the material texture gets transfeered but the color doesn't. the og obj is a probuilder obj if that makes a difference, and it has the default skin with a color applied.
go.GetComponent<Renderer>().material = otherObj.GetComponent<Renderer>().material;
go.GetComponent<Renderer>().material.SetColor("_Color", otherObj.GetComponent<Renderer>().material.color);```
Use sharedMaterial, read the docs
any clue why my paint details is not painting anything?
Painting trees work tho.
i tried to just paint cubes but does nothing either
im making a main menu for my game and when i press a button to activate the other part of the UI my music starts playing twice... anyone know why?
i did
Not without seeing code
theres no code, just deactivating and activating through the button
then why is it in a code channel 
is there a UI channel?
sure is #📲┃ui-ux
oh thanks
also clearly show the inspector for each event
like idk if it is that i cant start both audioRecordingSource and audioListeningSource at the same time, but dont know how to go about solving it
we answered your question already in #💻┃code-beginner
I also asked you to show your code in the other server and you deleted your comment
What is going on here?
mb someone helped me already was a raycast issue, wasnt aware I souldnt cross post
Alright. Yeah, crossposting is against the rules in every server I've ever been in. Just makes things super confusing
Glad you got it resolved though!
I have now encountered a problem. I added the ability to move down slopes by checking the difference in normals between the player and the ground. But I am experiencing an issue where, as I go up the stairs, I collide with the corners of each step and the game thinks I am on a ramp, causing me to fall back down to the last step (this could be caused by an issue with how I apply gravity on slopes but I;m not sure). Here is my script: https://hastebin.com/share/ewikekisay.csharp. Here is a video of the problem: https://streamable.com/5oo1wg
im new to community servers thats why I wasnt aware sorry
Man… adding stuff a game you last worked on 2 years ago is like…. Hunting for the right place to add one line of code and when you get there, wondering why you did all the stupid things…
World's hardest try not to cringe challenge is looking at your old code 
Hi! I am new to Unity, and I have a problem that I want to put a plugin to be able to put gifs and the problem is that I don't know how to put the plugin
"put the plugin"
yeah thats descriptive
lol
i need help fixing a small bug otherwise ill just add it as a feature can anyone help?
You should probably ask your question.
so yes got it
my 2d character sticks to walls
every
single
wall
floors and cielings too
Likely it's not a coding question and this is the coding channel.
The common solution for a Rigid body system is to add a material with zero friction else modify linear drag etc. Try asking in #💻┃unity-talk next time.
which plugin btw
bet
UniGif
so whats the problem with it
I don't know how to put the plugin
wdym
also is this even compatible with unity above 5+ ?
This is made with Unity 5.4.0f3 (Mac, Win, Android, iOS).
last update was 6 years ago
Ho, I didn't realize that, thanks for letting me know.
it might still work
download the folder and put it in your assets
ok
I think it doesn't work
you can just switch it like it says
sorry, I don't know much of English
but I will try
click it , it shows you where it is
and it should still work. Thats only a warning not error
ok
I am using that plugin because I want to animate the buttons on my menu, but the problem is that when I import the gifs the animation is not shown
it works
Im not sure this is what you want for that..
why not just export them as different frames and use unity Animator
good idea
this should work for example
https://ezgif.com/split
OK, thanks a lot
So as someone with 15 yrs experience doing programming for games, in a wide range of different peoples custom engines (and monogame), but only recently with unity, I have an observation that strikes me as really, really bad about unity and likely the underlying cause of peoples general perception of "unity games have performance issues, lag spikes/hangs in particular".
Which is: Any work the game ever does on gameobject(s) (enabling them at least, but likely material stuff, transforms, etc too), can only be done by the main thread, and not even in parallel.
So, if you want 60 fps, you have 16 ms of work done by a SINGLE core as the absolute maximum that will ever be possible to do in a single frame, even while your cpu usage is like <15% and other cores are idle.
Correct
In my case the game has around 5ms of work to do just pulling unity objects out of pools, putting them back in, and updating things that must happen every frame like transforms and materials -- which despite already laboriously being separated from all the rest of the game code since it has to be done in the main thread and unparalleled, it alone is also too much time for a single frame and has to then be time sliced ... and despite this effort spent, the outcome at best, is that some objects end up simply not updated every frame in ways visible to the player!
I think this is why ECS is here
Jobs too
Well, do those really let you have 4 tasks running in parallell, launched by the main thread (and blocked for completion at the end of the main thread update), which are enabling/disabling/updating transforms of a quarter each of your game's unity gameobject's?
Ecs doesn't work with gameobjects
And jobs would be best inplemented as work that isn't directly affecting gameobjects (or with ecs), and then handle gameobject stuff on the main thread. So calculations that you can do, then bring it back.
https://www.twitch.tv/videos/1517796421
They talk about how they leverage ECS
unity went live on Twitch. Catch up on their Software and Game Development VOD now.
But yeah, jobs can be threaded easily
See i don't understand how that would help the situation at all. I already know how to parallelize work and don't need unity's help for it. And do to necessity have already (annoyingly) entirely separated gameobject work from everything else. The problem is that ultimately its still blocking the main thread while idle cores cannot help.
Yes that is correct. These are alternatives, not something that will change the main thread/monobehaviour issue
That's just something you're gonna have to get used to if you want to use gameobjects
You might want to ask more in #archived-code-advanced though
What is the correct way to bind a child class, its parent and all implemented interfaces using zenject?
Container.BindInterfacesAndSelfTo<Child>().FromComponentsInHierarchy().AsSingle();
Container.Bind<Base>().To<Child>().FromResolve();
Is it OK?
Does that vid go into an alternative that doesn't involve gameobjects? I guess I don't even know what that would look like ... immutable transform structs or something? I'll watch it in any case.
No idea, I didn't post the vid.
But ECS works with entities, not gameobjects, so it completely sidesteps the issue
The DataOriented approach allows threading for almost everything (maybe everything?)
Oh, i haven't groked the difference between those two yet.
https://youtu.be/Bz24Jp30nkM?t=304 this should help
🔽 Download Unity 2022 LTS - https://unity.com/releases/lts 🔽
📃 Unity Devblog - https://blog.unity.com/devblog 📃
🦅 Follow me on Twitter - https://twitter.com/TurboMakesGames 🦅
💬 Join our Discord community: https://tmg.dev/Discord 💬
🔴 Livestream with Dani: https://youtube.com/live/EWZ3cq7cims 🔴
💻 My Game Development Setup: https://tmg.dev/GameDe...
I was gonna explain my understanding, but I think asking in #1062393052863414313 might be better. Someone like Tertle or Issue knows way more about the underlying architecture.
Basically entities are just indexes to a chunk of memory though, and the component structs are grouped in that chunk of memeory. Systems iterate chunks containing archetypes of entities (an archetype being the same components).
That's an extremely basic rundown of course
The things that need to be on the main thread are things like structural changes (adding removing components), but most of the rest can be implicitly threaded
Is there a good way to grow/show a spriteshape over time? It seems like it might be expensive to constantly grow the actual spline, I basically want to set the equivalent of a normal filled sprite's fillAmount property
Ah ok, im familiar with that design paradigm. But, its main benefit to performance isn't that it makes threading easier, it actually makes it much more rigid and ends up with quite odd public apis unless its only used internally. The purpose of this design is to improve performance not necessarily via threading, but via contiguous memory access -> better memory cache performance.
Correct. It's all about data locality. Threading is merely a side-effect
But I thought that would make it relevant.
Basically nothing can be done about the main thread issue with gameobjects as far as I know
If this were someones own game engine, id think the very first thing one would do upon hitting this issue, is to find the calls in question they need to do in parallel, and simply make them threadsafe. Some internal Dictionary or List that needs to become a ConcurrentDictionary, some property setter than needs to use interlock-exchange, and then it would be fixed. Not only would that be less work than all the work-arounds ive seen, it would be less work for unity than inventing 2x new systems that aren't compatible.
There really is no proven solution. People arent using unity (gameobjects) when they want insane performance
Well, can you still use entities with transform components and meshrender components with materials?
I mean, I've never had issues with it in the decade I've used unity. You just.. get used to it haha. As long as you're conscious of the issue, you can do it all in the main thread no problem
I like Bevy for performance more honestly
Because i dont actually care much about the "GameObject" type in particular, but all of the above are fairly convenient.
You can bake gameObjects into entities and entities all have their equivalent components be it transform or rendering
If you are asking if you can use the regular gameObject.transform in ECS then no
Are these prebaked entities with x components then able to be enabled and disabled (added/removed from the scene) in parallel from arbitrary worker threads?
Probably better to ask the #1062393052863414313 people, doubt many people here dive deep into it
Anyways I also havent had any issues with performance. You really can run a lot. Once you start looking into big multiplayer games or massive amounts of objects (factorio like) then you need something else for sure.
Thanks for all the responses in any case! Yea at a certain scale, you have to decide "what is an entity" and what needs to be a system for handling 500x live bullets/shots that are not entities.
If anyone wants something similar, I was able to roughly get the filled sprite shape behavior I was asking for by just animating a mask over it
Is it like a bullet hell game? 500 doesnt sound like a maaaajor problem and realistically this would be the "hot zone" in terms of performance.
Everything else would likely be negligible
Actually im a modder and contributer to AIW2 (ai war 2) which is a space rts. It can have upwards of 1k 'ships' on a single planet (which is the unity scene) and equal numbers of live 'shots' in motion. But both of those end up being stacked or compressed into for example "10x Foo" as one object as numbers increase. But the visuals for that stack of 10x is actually a little heirarchy of entities anyway, from a prefab.
Hey all. I have a Brain class with a static variable here
public class Brain : MonoBehaviour
{
public static UnityEvent BrainDiedEvent;
}
Inside my GameManager script i have this
void Start()
{
Brain.BrainDiedEvent.AddListener(OnBrainDied);
}
I'm getting a null reference exception which doesn't make much sense because the variable is static. I'm able to access other static variable from this class but not this one for some reason.
I don't know what UnityEvent is, but unless its a struct, you are not actually allocating it.
Even if it is a struct, doesn't unity do something odd with static initialization?
UnityEvents are for displaying events in the inspector, if it's static it's not serialized, so it probably shouldn't be a UnityEvent
and should just be a normal event like an Action
I'm not seeing this in the docs?
A zero argument persistent callback that can be saved with the Scene.
Doesn't say that its only meant for displaying it in the inspector
But it should still work as an Event right? Should still be statically accessible?
I mean its simply null is the issue right?
Yeah
If it's static, it's not being saved, it's not being configured in the inspector, and you're just incurring a worse API that requires you to initialize the event or else get an NRE
its a class according to the docs, you need = new UnityEvent
If you used a normal C# event like an Action you wouldn't have this problem at all
Because they initialize themselves when you += subscribe to them
a UnityAction or an Action?
well, i dont think you can += an Action as thats not a multicast delegate is it? hmmm
C# Action
huh
Delegate is just multicast delegate
i have an old misconception (though likely a common one) that for the += operator to be used, it has to be something defined as an "event"
event just means that the delegate can't be reassigned externally
C#/VB/F# compiler playground.
it would certaintly be a lot less... unexpected, if Action.Invoke() was calling a single method, and Event.Invoke() was more than one potential method. /sigh oh wells
Action is just a delegate that takes no args and returns nothing. Theres nothing really about invoking one method vs many
Yep. I just re-forgot that, over the last 3 years since i was in that deep ;D
(goes to refactor List<Action> _callbacks i wrote yesterday)
Hey, I want to activate every gameobject in a given array, but this script only does it to the first gameobject in the array.
Is there a better way to write this?
the foreach loop will iterate over every GameObject in Lights, there's not a lot going on here - likely whatever is happening is somewhere else
then the condition isn't happening
it works when i put it in the update function
foreach (GameObject Lights in Lights) feels weird
But i only want it in start
Hey, I'm just looking for some general advice if anyone has input. I'm hoping to develop a system where when a player kills a boss they'll unlock two new abilities that can be interchanged with three possible slots. This would obviously require some form of persistent memory but would a scriptable object be a better way of approaching this or an interface?
seriously lol
to be blunt, you're doing something silly, somewhere - it could be any number of things since you're accessing global static properties, I could guess 5 different things that would break this, but you'll probably learn more if you study everything you're doing from start to finish and find the problem yourself
Remove the if statement
godda be that
Both a scriptable object and interface dont make sense here. An interface is just a way to enforce a class to implement something. SO shouldn't be used for saving data.
You can write to file in a format like json
nope it works now
maybe I didnt save the script before
thanks for the advice i guess
Oh for real? My bad, is there any documentation on unity? Or should I just look for videos on the matter.
I appreciate the input, not super new to coding but still new to unity and C#
There are tutorials out there, newtonsoft (for json) is a commonly used one.
And yea SO data isnt used for saving. In the editor it will save because you are directly modifying the asset. In a build it will not save
You might use a SO or interface while loading this data, but the data will ultimately live in a file
If you don't fully understand what you're doing, don't modify the data in scriptable objects that come from assets.
you'll just cram your data into a plain old C# object (one that doesn't derive from any Unity classes) and then serialize and deserialize that
Okay, other than handling how the data saves, the ability system itself and be an SO no? My team wants it to be modular so we can expand and remove on the fly.
Ahhh okay
you can store ability definitions as scriptable objects, yes
I'll try to putter around with it for the time being and get back to you guys when I actually have a prototype to show off
Thank you for the input @heady iris @lean sail
Hi, I have this code that's meant to move a UI element to the screen position of another object. It works when playing in a certain aspect ratio, but when playing Maximized, the UI element is way off. How do I fix this?
swordIndicatorUI.rectTransform.position = mainCam.WorldToScreenPoint(thrownSwordPrefab.transform.position);
The difference
The Canvas is set to scale with screen size
im not entirely sure if this is a advanced question or not, but im trying to fix my ai. Right now i have the ai so where it will just run around, stop periodically, then keep going. And it does that for the most part. but sometimes it will get stuck and it will just spin and never stop unless i reset the play mode
!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.
Hi everyone, I have code that controls how slow time runs in my game, I control Time.timeScale with a variable called realTime, I have an upgrade called timeSlowSpeedLevel, and my code says realTime = 1 - (timeSlowSpeedLevel * 0.1f)
when the speed level is 1 (making time slow to 0.9) it works fine. When speed level is 2 (time SHOULD slow to 0.8) it flickers between 0.8 and 0.7
I have no idea why
Are you sure the variable timeslowspeedlevel is steady at 2 and not alternating between 1 and 2 for some reason?
Or rather between 2 and 3
no it also happens level 5, it flickers between 0.5 and 0.4
but when time is 0.9, and 0.7 and 0.6 it works as intended, staying at those values
nothing changes the upgrade level other that pressing the upgrade button in a different scene
it may be the actuall time slow transition method, getting it now
I don't see an issue with this code
can i use round to lock in into the nearest tenth?
nevermind, I resolved it, thanks!
I’m declaring a public gameobject within the class but now whenever I reference it it always gives me an the error “the name ‘myGameObject’ does not exist in the current context”. I don’t understand why
I’ve tried referencing it everywhere and nowhere works
I’ve even tried referencing it on the next line so I don’t think it’s a scope issue
This is definitely a #💻┃code-beginner issue, but also you should show your code and the exact error. Likely you didnt make it public, didnt save the script, or are referring to the wrong type.
Show the !code
Hard to say without 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 don’t really know what to send for my code I’m literally just declaring a public GameObject
But I can’t use it anywhere
The code where you declare it and where you try to reference it 🤷♂️
What else?
public GameObject myObj;
Vector2 point = myObj.transform.position;
Are both lines in the same script?
Is the myObj line a class member?
Yeah they’re right next to each other
Like right next to each other inside or outside a method?
Then of course that wont work, you cannot define the value outside of a function like that
myObj wont be assigned by that point
Why
Do some c# basics before unity. you'll greatly benefit it
I told you why in the message above
I know c# before I downloaded unity
Is there a way to check if a point is in a 3d collider? I can use Physics.OverlapSphere with a radius of zero, but I am only comparing against one singular collider which makes this terribly inefficient.
I am trying to make a basic rope using Verlet integration, and this is how I was going to handle collisions: https://pastebin.com/eBb3ENEA
Did you put this as class members or in a method. Either way, where do you assign myObj?
This is a pure c# issue, not unity
Sorry but clearly not
You can definitely assign values outside of methods in c#
I think it would be helpful if you shared more of your code.
You cannot assign it based on myObj because #archived-code-general message
Wait, these are class variables? You can't reference another class variable when defining a class variable.
Yes, no one said otherwise
But you never DID assign it. Just declared it
Maybe you want to use this
https://docs.unity3d.com/ScriptReference/Bounds.Contains.html although I dont know what you exactly want because your description says a point within a 3d collider but also overlapshere with 0 radius. If 0 radius you could check if the position equals the starting value
That is... not even relevant to the issue
MyObj is the issue
Again, you'll greatly benefit by doing more basic c#. You cannot just randomly guess where to put it
And we've written already that the assignment you're doing cannot exist outside a function
Field initializers cannot refer to instance members.
The compiler explicitly tells you this in the error message.
Oh I also see what you meant by 0 radius now, I was thinking of it in reverse.
If you want to write the object's position into a vector, then do it in Awake.
you can't just randomly move stuff around until your code happens to work
this produces junk, not code
I was thinking about this wrong, I actually only need to push it in one direction regardless of which side it's on, thanks for the help though.
Actually, nevermind.
It does matter.
I confused myself.
Uh... maybe for now I will just treat them as points.
//Toy is the alias of the sprite renderer sprite
public void SwapTexture(byte[] texture)
{
toy = Sprite.Create(new Texture2D(64, 64), new Rect(0, 0, 64, 64), Vector2.zero);
toy.texture.LoadImage(texture);
toy.texture.Apply();
}```
Am i loading in this texture wrong because the texture isnt showing whenever i put it into play mode
Could I please get some help with this, I'm still stuck.
It's hard to look this up without getting answers about how to implement persistence. In my case things are persisting between scenes that I don't want to. I'm not exactly sure how, as I havent set up any persistance.
When all the waves of the game are finished or when the player dies a button appears to restart and when you click it i simply call
// GameManager.cs
public static void Restart() {
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
And then state starts breaking with my spawner and UI and i get some null reference errors that i dont get when starting the scene the first time.
I believe I'm running into this issue. Hm, so if you need something to be static and also need it to reset beween scenes is there a good pattern besides manually writing reset code?
private void Run()
{
float runSpeed = speed *= 2;
if (!isRunning && Input.GetButton("Run"))
{
speed = runSpeed;
}
else
{
speed = speed;
}
}
how do i make the else not so, bad
please

speed = (!isRunning && Input.GetButton("Run")) ? runspeed : originalSpeed;
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator
Gotta have an original speed though, because you are setting speed, so setting it back won't change it
private void Run()
{
float runSpeed = speed *= 2;
float originalSpeed = speed;
speed = (!isRunning && Input.GetButton("Run")) ? runSpeed : originalSpeed;
}```
like this?
@spring creek
Yeah, but you can probably do original speed outside the method.
Either way works though
Well actually
You are setting orignalSpeed after setting speed to * 2
*= is an assignment
So you are setting speed AND runspeed on that first line
so =*??
Are you doing this every frame? Isn't it going to double the speed every frame?
no it isnt doubling every frame
but my speed doesnt go back to normal
i set it to 1.5 it was good
but when i let go
it kept that speed, and when i keep pressing shift i speed up again and again
Just for cleanup, consider this
public class Whatever : MonoBehaviour {
[SerializeField] float currentSpeed;
[SerializeField] float runMultiplier
[SerializeField] float normalSpeed;
private void Run()
{
currentSpeed = (!isRunning && Input.GetButton("Run")) ? normalSpeed : normalSpeed * runMultiplier;
}
}
or even a hard set runspeed, but whatever
That way you get rid of the magic number though, which was the big part imo
Im not sure about a specific pattern for that, though you could make a "scene loader" and fire an event when the scene finishes loading, then your spawner, UI, etc can reset itself when that event is called - or if those classes are meant to be DDOL/monos you can put them in a scene script that recreates them when the scene loads (similar to dependency injecting, having a list of "dependency" prefabs to ensure are in the scene) - generally, if something is static its going to persist unless you decide to clean it up yourself or tie it to another system that manages it
Im not quite sure what could be causing your issue, though a few things you can do to help yourself debug is make your slope values public or log them every frame along with your hit normal so you can see what condition might be causing your code to trigger, its possible because the surface of your steps are probably 90* the math is coming out as 0 or something - you can also try a git package called "Verxyz Debugging", it visualizes all Physics and Physics2D casts, shapes and their collisions so you can see exactly whats going on
Hey I'm getting confused by local and world vector3 stuff, so what I want to do is get a point that I use as a pivot for an object, Like if i shoot a ray and it hits near the top of an objects collider, thats the point I need. But, if that object is moving and rotating, I want that point to remain in that position relative to the object.
Does it happen to have anything to do with Transform.InverseTransformPoint? (I don't entirely know what transform.inversetransformpoint does either, to be honest)
If it matters, this is for a half-life style pickup system, cuz if I say wanted to open a door, I need the force to be applied from the point where I aimed at so I can open and close it easily
You'd need to store the the point relative to the object position/rotation,which is also referred to as local space. You can achieve that by using inverse transform at the moment you want to cache the point, as it transforms it from world to local space. Then if you need to get the that point in world space later on, you can use transform point, to transform it back from local space to world space. You can also do this manually with some math.
OH wait I get it now, thanks 👍
Is it common knowledge that there's something wrong with the cloth compontent in unity? I tried to add it to a prop but it kept crashing unity, painted the weights and saw it running ONCE, and then tried defining a force to see some movement, and now even though I reset the movement back to 0,0,0 it's still crashing.
It's pretty unstable yeah. It's easy to do something wrong with it.
I'm using a scriptable object based inventory system. I also use the same system for chests and store inventories.
Everything works fine for static items, health pack, keys, weapons, etc. But I also want to have a few items that have randomized data. For instance a gold item in a chest that can have a randomly set value range. The inventory slot holds the item data scriptable object and all of the methods involved with the inventory system reference the base item data scriptable object.
is there any editor utility for editor camera? like show the position, rotation and possibly edit it? Or do I have to write my own script?
Scriptable objects aren't really made for this, but you can create copies with Instantiate (like you would with a normal prefab) and change the clone's fields. Note that the performance is going to be a lot worse than if you just used basic C# classes and objects.
Could anyone help me using the Resources.Load function in Unity?
I'm getting an error saying the asset can't be found but I don't see what I'm doing wrong:
AudioClip dialogue = Resources.Load<AudioClip>(dialogueAudio);
if (dialogue != null)
{
Debug.Log("Successfully found the audio clip.");
}
else Debug.Log("No audio clip found.");
No audio gets played (I try and play it further down in the code) and the second Debug Log prints out
You'll have to show what dialogueAudio contains, preferably by debug.logging it
It seems to be the right path as far as I'm aware
unless I'm misunderstanding something about it which is very possible haha
Read the docs again
Note that the path is case insensitive and must not contain a file extension.
Hi! I'm trying to access a leaderboard on buckets from unity cloud clode js, but it gives me an error " "detail": "Score submission required to view the scores of this leaderboard"," Can someone help me?
const getScoresResult = await leaderboardsApi.getLeaderboardScores(projectId, "LdbId");
SOs should not get instanced at runtime
it is against the whole point of SOs
and since SOs are not made for this, they have interactions with loading, scenes, and GC (or lack thereof) to keep them persistent in ways that are normally wrong for things instanced at runtime
the whole point of an SO is to create instances that exist as files. They exist outside of any scene, they exist before the game even starts up, and their information persists even when things get nuked
If you need to actually save persistent data, you need to save to an actual file (not an SO).
because SOs get reset whenever you open the application
@dull temple
Also, it will cease to be “less effort” once you need to put in effort to fix all the bugs and unintended behaviours to address the aforementioned issues
hello, i got an issue in my build that i dont have in my editor
i got a script, that is attached to one GO.
it holds data that i want to keep between scene loads, so its static :
public class CrossSceneDataHolder : MonoBehaviour
{
public static bool InstantStart = false;
public static bool StartInTuto = false;
}
i use it in one script before & after loading
// elsewhere
public void Restart()
{
CrossSceneDataHolder.InstantStart = true;
CrossSceneDataHolder.StartInTuto = _playerC.InTutoLevel;
SceneManager.LoadScene("Game");
Time.timeScale = 1;
}
// elsewhere 3
if (CrossSceneDataHolder.InstantStart)
{
CrossSceneDataHolder.InstantStart = false;
if (CrossSceneDataHolder.StartInTuto)
{
CrossSceneDataHolder.StartInTuto = false;
StartTutorial();
}
else
{
StartClick();
}
}```
in the build, well, `elsewhere 3` doesnt work, so my guess it that the static fields are reset
any ideas why this occurs in build ?
Is there any way to make the Value property visible in editor?
public class Setting<T> : SettingBase
{
public Setting(string name, T value) : base(name)
{
BaseValue = value;
}
public T Value
{
get => (T)BaseValue;
set
{
if(value is not null && value.Equals(BaseValue)) return;
else if(value is null && BaseValue is null) return;
BaseValue = value;
OnValueChanged?.Invoke(value);
}
}
public delegate void ValueChangedEventHandler(T value);
public event ValueChangedEventHandler OnValueChanged;
}
[field: SerializeField] apparently only works on auto properties
and this solution i found there https://forum.unity.com/threads/serialize-c-properties-how-to-with-code.506027/ requires the attribute to be placed on the backing field which i can't do because its an object type
Unity's serialization only works on fields, that's why you can do it for auto properties, because they have an associated field
Regular properties are just special functions, the serializer knows nothing about them
You'd need to write your own editor for the component, or mess around with the com.unity.properties package which has some kind of support for properties afaik
designers do not create SOs during runtime.
SOs can only premanently be modified in editor play mode or in inspector
anything that modifies an SO during build will not work, because SOs revert to initial state whenever the built app is relaunched
if you made an ingame editor that could only be used in unity editor by designers, that would technically work
reread which part
designers instantiate SOs primarily within unity’s editor, using the right click create asset menu. then modify via inspector.
We were originally discussing making SOs via Instantiate during runtim (ie not in unity editor), which is totally different.
I found an alternative. Just moved the BaseValue from the SettingBase class to the Setting<T> class so i can use the Attribute i found in the forum thread
Tho it means i can't do SettingCollection["setting"].BaseValue as Type and need to do SettingCollection.GetSetting<Type>("setting").Value instead
It won't be as efficient as directly accessing the field, but you can have a protected abstract property in SettingBase that you override in Setting<T> that gives access to the field
Or actually, is BaseValue a property too?
In that case you can keep it on SettingBase and put this in Setting<T>:
[YourAttribute]
public new Type BaseValue => base.BaseValue as Type;
any ideas ?
I don't think there is enough information to answer it, because from that sample code, it should function as expected (though I'm not sure why it's a MonoBehaviour if you're not using any features of MonoBehaviour)
well, i dont have anything more to show, thats all my code related to this
Have you checked the log file from the build? Are there any exceptions happening prior to that code?
You can run the game with -logFile path/to/file.txt if you don't know where to find the log (it's usually somewhere in appdata)
!logs
%UserProfile%\AppData\Roaming\ and not %AppData%\? Weirdly verbose lol
found it
Is CrossSceneDataHolder in a .cs file that doesn't match its name?
it just did a test by removing monobehviour after what you said, going to test again with
Oh
You'll get that error because you still had the component on a game object
You need to remove it from the game object before removing the inheritance
ah okay, i added it to a GO because i firstly thought that unity didnt build with it
Nah, it'll be kept around
IL2CPP builds will remove unused code, but since you have code that actually uses the class, it'll still stay
does a class has to be from MonoBehaviopur or scriptable object ?
No, it only needs to derive from MonoBehaviour if you want to attach it to a GameObject
And it only needs to derive from ScriptableObject if you want to store it as an asset
Right.
In this case, you basically have a singleton that doesn't use any Unity callbacks, it's just a data container. So it can be a plain class
Now, if you want to create a Unity object, you need to have UnityEngine.Object as a parent.
ScriptableObject is there to let you do that with non-MonoBehaviour classes, pretty much
A Unity object is something you can drag around in the inspector
materials, mono behaviours, game objects, textures, audio clips, text assets...
In other words:
ScriptableObject = custom asset
MonoBehaviour = custom component
so for my CrossScene... class, i should make it derived from ScriptableObject ?
You don't need to, no