#archived-code-general
1 messages · Page 365 of 1
IPointer guys most definitely work with physics if you add a physics raycaster component somewhere
i added to my camera
but with 2d elements dont really works
i have a lot of videos of 3d and i see definitly works
There's a 2d variation of the component I'm pretty sure
but y try with a blank scene dont works
physics2d raycaster
dont works
never works xd
Of course it does
but works perfectly fine with UI elements
I've used all of these at some point
Yes with colliders
Ah.. well not sure in 6, but unlikely they broke it
Perhaps something else was blocking it?
btw
nothing is blocking it
i dont know why dont works
i already see that
my events system in here
i try with trigger
matrix layer
layers
raycast padding
nothing works
normal collider
The classes are pretty basic. It's unlikely that they don't work. It's some config issue.
That's gonna work a lot less
post a screenshot of the inspector of your camera.
Also please post in full sentences, shift+enter exists
OK, and show the inspector of the object you are trying to detect
1 max intersection could be a problem
i try with 10 and 200 and 20000 noting works
Keep higher while figuring out
those look fine so it may be your code, post it to a paste site
i make it with UI elements and works perfectly fine with 2D objects dont works
it a debug
did you put the EventSystem and did you put the proper Physics Raycaster 2D on the camera
yeah
Here event system
here raycaster
post full code
I wonder if new input system messes with that. gonna double check rq
i ready posts and more of that the same problem with a lot of people
works for me ig
I want to see the full code
not for me :T maybe the reason is because i'm using unity 6?
shouldnt be an issue, can try later
in play mode, open the event system game object, go to the inspector, open up the bottom part of the inspector with event system info, hover with mouse over the object and take a screenshot that shows it
your input system are not the same
my new event system only works with UI elements
if your camera has a PhysicsRaycaster or PhysicsRaycaster2D (depending on the physics system you are using) then it will work with world space objects too
that's what we said, but apparently not
i can assure you that it does. the objects being detected will obviously need a collider and of course be on a layer included in the raycaster's layer mask but it does work
also what we said 😄
my object have a collider
BOXcollider 2d
my camera have a physic raycaster 2d
i have all :I
but i have nothing XD
show the full code
the event system doesn't seem to be detecting it (or so it seems in the last screenshot I asked for)
There is
might be some issue with the position not being correctly setup in the input system?
if your read my event system down show the same of yours
here in selected
mine is sucky though
I'm in a VR project
yours should have more data... at least it used to have more data last time I needed it... am too lazy to set things up now to test though, sorry
good luck with it 🤞
does your EventSystem even detect UI objects?
yeah but as I mentioned the PhysicsRaycaster makes it work for Colliders
You just need to still have EventSystem ofc
i try with physicsRaycaster and Physics 2d raycaster
the same result
the GIF i sent u earlier thats a sprite with circle collider
nothing happens
yeah i know
but its a strange thing i dont know XD
i dont know how to fix it
i assume is a method for UI elements
i make a empty scene an try with a basic script
the same result
it usually is yes.. something else is wrong
I will try it on 6 rq but I doubt thats the issue
show your event system working for UI objects
wait
well..works with 6
uh i have no idea
did you test the UI objects ?
here's a stupid question, but have you actually clicked into the game view window
^yea did this before . Double check you actually focused in the gameview by clicking on it after pressing play
YEAH HAHAHAHAH
I'm pretty much at my wits end, I'm using unity6 and I noticed that I'm not launching scripts according to the hierarchy, but it looks like their sequential launch depends on when I added it to the scene (the so-called script that I add last is launched first).
Has anyone encountered this before? I'm pretty desperate
there is no guaranteed execution order for your components. they have never been guaranteed to execute in order based on hierarchy
if you are relying on that assumed behavior then you have a serious design problem
afaik they more or less rely on the instance id number, you should probably control the flow of the timing yourself
Well, I don't know, I never relied on it, but at least we didn't notice that it ever worked differently.
pretty simple, use a combination of Synchronous code to initilize them, and events, you should be ok.
Pretty sure the parent/child hierarchy is respected (?)
are you confusing UI rendering order?
But that's exactly what I'm trying to do... The problem is that the playerManager is the very first in the hierarchy, but it's called only after the Controller assigned below
remember, do self-initialization in Awake and don't access other objects until Start to ensure you are not accessing something that has not yet been set up
I dont have initialized reference
yeah you should not be using the hierarchy to control your flow.
No — Awake is respected for sure, surely not Update methods tho
I say for sure but I really mean “iirc”
Whatever it is respected or not, it is not guarantee. Could be broken in a future release.
yeah I would never rely on the hierarchy no matter what
disaster waiting to happen
i dont even change the Script execution order
if you do that, you have flawed design most of the time (unless its some type of boostrapper script IG)
I’ve based a lot of my singletons on this lol.. it’s pretty handy.
if (…) DestroyImmediate(this.gameObject); and no child’s code is executed
Well, I don't know, but the problem arises when OnEnable is called on COntroller before awake on PlayerManager, which is a total fuckup, we've never had a problem with this.
this is meant for destroying assets not gameobjects no?
there is no guarantee that one object's OnEnable has been called after another object's Awake unless that first object was instantiated after that first object's Awake message had already been called
https://docs.unity3d.com/Manual/ExecutionOrder.html
Awake is only guaranteed to be called before OnEnable in the scope of each individual object. Across multiple objects the order is not deterministic and you can’t rely on one object’s Awake being called before another object’s OnEnable. Any work that depends on Awake having been called for all objects in the scene should be done in Start.
me trying to subscribe my Singletons events from OnEnable 😢
InstanceID -50312? 😮
none of that matters
the order that objects receive their Awake and OnEnable messages is not deterministic. You cannot rely on one object receiving its Awake message before another object receives its OnEnable message
Instanciate at runtime
Negative number means it has been instantiate as far as I know.
i think bigger negative meaning it was added last
if you save n reload the scene they will be positive
Seem like it is not necessary runtime instanced.
The instance ID of an object acts like a handle to the in-memory instance. It is always unique, and never has the value 0. Objects loaded from file will be assigned a positive Instance ID. Newly created objects will have a negative Instance ID, and retain that negative value even if the object is later saved to file. Therefore the sign of the InstanceID value is not a safe indicator for whether or not the object is persistent.
ah yes that confirms what I said
if you save n reload the scene they will be positive
so yeah instanceID def not reliable to depend on at all, I thought they were relevant to execution timing but seems not
I guess in a build a negative number is pretty much an instanciated object.
iirc thats how you only run 1 method once if objects with same scripts collide
checking if the instance ID is less
add a canvas and a button, see if its working (is the button hovered)
well shite
there is something incorrect in your setup then because IPointer interfaces absolutely work with world space objects provided that they have a collider and the camera has the relevant raycaster attached
you've got a 3d raycaster on there
i know
i'm trying everything xd
The InstanceID did get fixed after the reload, but the execution didn't. I never had a problem with the call, when we had scripts on 1 gameObject, they were called randomly as we assigned them, now it's completely random.
It even calls OnEnable on the WeaponController before awake on the playerManager
pretty sure we told you a couple of times, the instanceID would not change the order here
use an actual script to control the setup
Awake is only guaranteed to be called before OnEnable in the scope of each individual object. Across multiple objects the order is not deterministic and you can’t rely on one object’s Awake being called before another object’s OnEnable. Any work that depends on Awake having been called for all objects in the scene should be done in Start.
I prefer to use Events when you need another object to know another object is ready with data
You can use the DefaultExecutionOrder attribute and force execution order of some things
putting duct tape on a raft full of holes
Okay, change, after I added it under myself and reloaded the scene, suddenly it works. The first one is called PlayerManager and then only WeaponCOntroller ... So some fucking Unity status?
i really dont know how to fix it xd
hmm everything seems correct tbh..I bet its something obvious though
What do you not understand about you have no guarantee on the timing of that ?
You should not depend on Enable being called after awake on other object.
but i dont know why dont works
@willow magnet scripts runs lines from Top to Bottom. Create a Setup function or Init, control your own flow
do you have 2022 ? or can you try a completely different project
I don't claim anywhere that I want a warranty, but it was quite a problem when the controller was called first, where Awake was called, then OnEnable (for events) and then awake was called on the manager... Yes, I don't understand why when awake should always be performed absolutely everywhere and then jump to OnEnable
I don't understand why when awake should always be performed absolutely everywhere and then jump to OnEnable
we've told you why this is several times now
not i have the 6000.0.7f1 version
I tried it with 6000.0.3f works fine
Maybe try a blank project ?
its a blank scene xd
i'm going to try
could be some player settings touched, maybe overlooked
You wont know for sure until you narrow down
Yes, I know that Awake is always called first on all objects, that's the reason why I wrote that some kind of fuckup happened, because I've never experienced this behavior, but we also never used Unity6.
this is how it has always worked. and the documentation that you have been provided very clearly states that there is no guarantee that one object's Awake method will be called before another object's OnEnable method. that is the whole fucking point. and your entire issue.
I've never come across this kind of behavior... But after realloading the scene, it's suddenly called exactly as I need (interesting, isn't it?) and it's also interesting that a non-negative InstanceID was assigned.
Even wake on Playermanager is called before WeaponController, before realload WeaponController was literally called first.
alright you're clearly not listening so i'm done engaging with this
just because you didnt encounter before doesnt mean anything.. Thats why we plan for things properly and no just rely on chance.
the instanceID will have no relevance to your scripts order now, and how you should set it up. If you did before, it was by chance that it worked out until it didnt.. Never rely on what you cannot control
But I'm not claiming anywhere that it's relevant and that it's worn out because of it, it's just that it's interesting that as soon as I'm given a non-negative number after reloading the scene (which is even higher than the manager's), it's called correctly. Unity6 is not stable, so I don't understand why it couldn't contain errors, even in something like this.
So far it hasn't happened to me even once, it could be some unity state, property, anything that went wrong.
well thats why it said to not be Guaranteed.
its not broken, its by design
But I don't dispute it.
alr. was just confused on this statements then
Unity6 is not stable, so I don't understand why it couldn't contain errors, even in something like this.
No, it wasn't, I didn't notice problems with previous versions, certainly not in functionality with monobehaviour
Hey I have some issues with dragging objects.
basically all of these are the same prefabs
and I can drag items across slots on the bottom
but I can't drag them to the slots on the top ui
none of this code is working for somereason i have ran Debug.Log("") to make sure void Start is running and it is so im not sure why it isnt affecting my game
here is the code for dragged item: https://pastebin.com/XwfeJ3YX
and code for the slot: https://pastebin.com/HYwe0dHh
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.
which one the cursor? did you actually click inside the game view for it to take affect
oh.
good point
thanks
i would debug the raycast make sure something UI isnt blocking it
shoot a ray at OnEndDrag?
EventSystem can be inspected in Play mode you should be able to see what ur mouse is hovering. Or its probably something between the two images, in that case maybe print OnDrop
hmm thats weird
it logged that the correct thing was under the mouse
but it didnt enter OnDrop
also would double check this value ? transform.childCount != 0
or didnt run at all
isnt OnDrop the item that got dropped on?
actually there was something blocking the ray
same result with ui works but with gameobject dont works
public class PlayerBrain : MonoBehaviour
{
...
void Attack(){
if(attackInput.action.IsPressed()){
if(TryGetComponent(out CharacterAttack characterAttack)){
characterAttack.Attack();
}
}
}
...
}
public class CharacterAttack : MonoBehaviour
{
...
void Attack(){
if(equippedWeapon.hasSwingAnimation){
weaponAnimator.SetTrigger("Attack");
}
}
...
}
I've got this simple setup for triggering animations, but it triggers the Attack animation twice. I've read online that its because I'm checking action.IsPressed() instead of checking action.started. However I want the player to be able to hold the attack button to continuously attack. I'm not completely sure how I should deal with this.
it was a waste of time
new project ?
weird..
inputactionasset have anything?
I can send you a blank project where the setup is working, but unity 6000.4
then you can double check if its the editor or something
ok one sec ill put it on github
in new project you did New input system or old?
in same proyect both
in both proyects i use both
old and new input system
you set Player settings on both right ?
yeah
its going to ask you in hub the missing unity version just upgrade it to your version and hit Continue when it asks prompt. It might take a bit to rebuild project
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TriggerAnimation : MonoBehaviour
{
[Serializefield] private Animator ZombieIdleNew;
[Serializefield] private string zombieIdle = "atack1"
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
ZombieIdleNew.play(atack1, 0, 0.0f);
}
}
}
Not working
Define “not working”
Also you might wanna slap in debug statements at different sections to see what’s running and what’s not
!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.
public class PlayerBrain : MonoBehaviour
{
...
void Attack(){
if(attackInput.action.IsPressed()){
if(TryGetComponent(out CharacterAttack characterAttack)){
characterAttack.Attack();
}
}
}
...
}
public class CharacterAttack : MonoBehaviour
{
...
void Attack(){
if(equippedWeapon.hasSwingAnimation){
weaponAnimator.SetTrigger("Attack");
}
}
...
}
I've got this simple setup for triggering animations, but it triggers the Attack animation twice. I've read online that its because I'm checking action.IsPressed() instead of checking action.started and that this causes the triggers to stack? Seems pretty weird that the trigger doesn't automatically reset itself but im sure theres a reason. Anyways II want the player to be able to hold the attack button to continuously attack. I'm not completely sure how I should deal with this.
Pressed() iirc is held instead of PressedThisFrame
or performed .. iirc I havent touched events on new input yet
ahh ill take a look
can you show the transitions, maybe the clip is there twice
how could it call the function more than once anyways when its in update?
sure
which function because update runs every frame
doesn't seem like it unless im missing something
Well Attack() is called from Update(), so I'm not sure why changing it to a key pressed down check would change anything? it should still only run once and only trigger once
you don't want it once ? I'm confused tbh I rarely use trigger for held, if Im doing a held I typically just use a bool in animator then add a timer between
jesus yeah im not sure why im not just using a bool that is equal to whether the key is pressed mb
should work fine after that
thanks
sure, hopefully that does it
👍
Need help understanding what I screwed up here
I keep getting the error "MissingReferenceException: The object of type 'CanvasGroup' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object." after leaving the scene for another and then reentering the scene
The error pop ups here and I don't know why
https://gdl.space/oqomoqakes.cs
pScreenTotal was destroyed somehow but you're still trying to use it
But in the start function it still gets the new version of the comp each time the scene loads
thats in the beginning what about later on?
can you show the hierarchy
Sure give me a sec
Here's also the other script I have that deals with menu
https://gdl.space/onupojegip.cs
The objects with canvas groups are Pause Screen, Pause Screen Base, and Y/N Layer
You probably have some script maintaining a reference to your MenuPause instance that was also destroyed, and calling Pause() on it
Are you using any DDOL objects/scripts?
DDOL?
DontDestroyOnLoad
You are also using static variables I noticed
which are very likely to cause this kind of error
I don't think I'm using any of those
How are you calling Pause?
I'm guessing from a static reference or something
Show your full stack trace of the error
it will give us more clues
also you should link all these in the inspecor btw, no reason to use Find by name if they are all part of the scene together
private CanvasGroup pScreenBase;
private CanvasGroup ynScreen;
private GameObject ynInitial;
private GameObject pScreenPrev;
private TMPro.TMP_Text ynText;```
Better yet, reference the CanvasGroups directly
There is rarely a good reason to have a GameObject variable unless you plan to call SetActive on it only
This?
yep looks like it's being called from your InputManager class
show that code
My guess is you're failing to unsubscribe an input listener that you subscribed
that's a pretty common mistake
right so you're doing this:
player.Pause.performed += ctx => pause.Pause();
menu.Pause.performed += ctx => pause.Pause();```
but you never unsubscribe
and since you also never disable menu...
it's still being called
You're only enabling and disabling the Player map:
private void OnEnable()
{
player.Enable();
}
private void OnDisable()
{
player.Disable();
}```
Why not just do this:
private void OnEnable()
{
playerInput.Enable();
}
private void OnDisable()
{
playerInput.Disable();
}```
enable and disable the whole thing
You really shouldn't use static variables for this stuff though... it's a disaster
Okay that seemed to have fixed it
I'll give a look through my code to try and remove those then
Thank you for the help
what would be the best way to detect if my wheelcollider car is accelerating or deaccelerating to play the right engine audio?
Doesn't it accelerate or decelerate based on your code?
So it depends on your code.
it applies motortorque or brakeTorque to the WheelCollider. this doesent account for external forces or deceleration, only input
Why would external forces matter
Engine audio is based on how hard the engine is pushing
Aka, your input
engine audio is based on the RPM of the engine
if you want a realistic sounding car, you'll need a basic transmission and "gear" setup
you can fake most of that
engines have a torque curve, and they'll output different amounts of torque at different RPM. <-- this might be completely useless information for unity's wheel colliders because they're pretty wack
i figured it out. thank you
What are Physics2D.FIndNewContacts and Physics2D.SolveDiscreteTraversal and why are they taking so much cpu? With 2500 enemies these 2 take up 56%, according to non-deep profiler!
Some information about the environment - 2d sidescoller, this enemy can only(!) collide with ground and walls and I don't think there are any enabled colliders aside from walls, grounds and these enemies(which should not collide with each other at all). What in the world creates these discrete islands in such quantities(I've seen 25k at least once)? Should I forget about the convenience of dynamic rb 2d and switch to kinematic or something else entirely?
how are you moving objects and what is the purpose of those functions for your usecase
Can you share the profiling data(as a screenshot)?
Is there any easy way to compare generic values when im messing with these kinds of values, structs and objects? or should i just have some sort of abstract function that they need to implement
[System.Serializable]
public class BoolSetting : ValueSetting<bool> { }
[System.Serializable]
public class FloatSetting : ValueSetting<float> { }
[System.Serializable]
public class IntSetting : ValueSetting<int> { }
[System.Serializable]
public class StringSetting : ValueSetting<string> { }
[System.Serializable]
public class Vector2Setting : ValueSetting<Vector2> { }
[System.Serializable]
public class Vector3Setting : ValueSetting<Vector3> { }
[System.Serializable]
public class ColorSetting : ValueSetting<Color> { }
[System.Serializable]
public class ObjectSetting<M> : ValueSetting<Object> where M : Object
glancing online at some of the c# interfaces but they dont seem to cover all my usecases in a simple way
purpose I don't know. These are Unity internal methods.
My code for movement is simple and yes, I know you should never use transform to move rb 2ds.
_rigidbody2D.linearVelocity = new Vector2(direction * _speed, _rigidbody2D.linearVelocity.y);
ohh those are functions that appear in profiler yes, makes sense.. Yeah moving transforms directly on rb would've been worse because the physics would have to "catch up" and thats costly too iirc
do you have very complex shapes? (like polygon collider ? )
ONE BOX COLLIDER 2D XD
on each of them, but still.
it still sounds like a lot of dynamics rb at once, but I havent profiled Box2d engine too much
do they all need to be active at once?
its generally cheaper to keep them as simulated = false until you actually need them
2500 to be exact.
yup
simulated = false sounds interesting but they still need to move somehow. They are active on a rather small scene
dont they have a Physics2D section on profiler
are they all seen by player at once?
well, no, but still something needs to be done with off-screen enemies because they should live their life, which includes eventually coming back to strike XD
What I mean is, I cannot just block their movement.
Or disable them
not block but do they all need physics simulations ?
they can be moved with transforms while not seen , depending on the game pfc
also are there any enemies clumping colliders together when inside/outside of screen ?
Actually, the whole idea for the dynamic rb2d was to implement a simple leap XD The whole point of this box collider is to not fall into the ground. Target raycasting is done using appropriate hashsets anyway(+ Bounds).
the collider isnt issue as much all those dynamic rbs calculating so many collisions / changes in contacts
you mean enemy in bounds of a different enemy?
oh i mean like a bunch of enemies stuck together or something
imagine enemies stuck together and multiply the imagined situation by 100x to get somewhat close to the madness I have XD
What I mean is - yes. They all are a giant crawling carpet.
btw what did Physics 2D section of profiler say, esp for total contacts
yeah that could be an issue
but I don't see how to fix it. Just to make it clear, the layer enemy1 vs enemy1 is unchecked
this is the section actually
oh i missed the second screenshot mb lol
i even screenshotted it xD
yeah that is wild amount of processing
Yeah, might as well forget about convenience and remove rb 2d from all enemies ^(
Yes XD
that doesn't mean that all 2500 dynamic rigidbodies are not each checking for new contacts every physics update
2500 dynamic rigidbodies is quite a lot, and if you are keeping them awake and simulated then they all must update every fixed update
Hmm. But what if I toggle simulation only for leap ability? and remove the box collider 2d. Just, anything else aside from leap can be handled by rb set position..? But that would mean Raycasting, one for wall facing and one for ground... need to compare and see what is more performant actually! Might actually be a better way.
btw it aint the box collider issue, its the dynamic rigidbody causing issue
if anything put rb.simulated = false when not in use
Yeah, the collider is just not needed anymore because everything will be raycast-based
Really interesting to see the performance difference XD
raycast fairly cheap
you still need colliders for other static objects for raycast to work
or detecting other moving
for ground and walls you mean? yeah, that's needed. But the collider on enemy was a single-purpose one - not fall through ground XD
you dont want your enemies to ever be detected again?
raycasts are very cheap. I tested 1000 raycasts using Physics2D.Raycast and it averages 0.32ms for all 1000. of course that was in a completely empty scene so i'm sure having colliders and other bodies in the scene will probably impact that, but it is still very cheap
oh, forgot about it 😅
has anyone tried unity muse for coding?
is it better helper than chat gpt or alike?
if its made by unity perhaps it knows about most things unity related unity muse i mean
nope
half the things it said were incorrect and most of the docs links were broken, who knows if its fixed..
not worth the monthly cost
gpt performed better in most cases
that's a problem, however
I start to think I can try to code leap with no rb 2ds XD
physics is dull
No point in having a lag spike on leap state on spawn enemies
ahh well i had no idea that happened
my last hope in rbs are kinematic ones, and then I switch to pure transforms XD
if the point of the rb is to respect collisions, then making it kinematic won't help. kinematic bodies are not affected by outside forces, including collisions
no, kinematic for enemy to be a proper raycast target. All movement including leap is on my side(hopefully)
it doesn't need a rigidbody at all to be detected by a raycast
yeah, but from what I know its a bad practice to move colls without rbs
and these enemies move
if you implement your own collision checks it won't be a problem. the issue mainly stems from the fact that moving the colliders doesn't respect physics
no, not that. I've heard somewhere that it is an advice from Unity to move colliders best with rb attached because otherwise you get a recreation of this collider every frame because it's internally bound to a hidden static rb in a scene... Memory falls short where or when, but "the issue mainly stems" is not exactly correct afaik.
you've "heard somewhere" so provide a source
your info is more than a decade out of date. that hasn't been an issue since unity 5
https://discussions.unity.com/t/moving-gameobjects-without-colliders-and-rigidbodies/768850/6
and was a 3d issue only
either way though, your performance concerns are going to be more about how you get 2500 moving objects to not run like ass without using DOTS
my target is webgl 🙂
not with 2500 dynamic objects it isn't 😉
this I think was the source. I might have misunderstood the info though.
saying moving object with collider is like moving it with rigidbody behind the scenes (colliders are physics)
if you have both a rigidbody and collider while moving it with transform the physics has to calculate more to "catchup" the two rbs , seems
Hi ! Question concerning AssetBundle: if I use LoadAllAssets(someType) to load a portion of the content, then later use LoadAllAssets() to load the remaining content, are previously loaded assets loaded again ? Can't find information about that kind of filtering mechanism in the documentation.
you could test it
Is it possible to change soft shadow quality in URP programmatically? Everything I find is changing the shadow resolution - I want to change the quality in this dropdown with code if possible:
Pretty sure the usual way to do this is to switch to a different URP asset
Hmm that sucks - not ideal. I guess I'll just give the player the option to set soft shadows on or off, without being able to change the quality. For those curious in case you're searching Discord:
URPAsset.supportsSoftShadows = bool;
(im not really sure where to post this kind of problem so ill just post it here)
so im currently using unity's navmesh system, and I pretty much want to make a moving obstacle walkable and non walkable at certain times during runtime, problem is it wont even be walkable when i start the game, i already used stuff like navmesh modifiers but it just wont work
ty
If you tried only in a empty scene, that's expected, cause the raycast just doesn't do anything, it has no mesh to collide with, it has no checks to do
Hi folks, I hope you are doing well, I am new to this server, I need some information about Nethereum and Unity. I want to do transactions through Unity and want to use metamask wallet I need the code of Unity C#, can anyone guide me?
I have a vector. I want a quaternion rotation that is aligned with this vector. Any good helper methods for this?
i dont think the unity devs are just going to give you unity source code lmao
if im being honest
LookRotation should be exactly this
Ya found it 😛
guys i made a script that spawns squares in a limited range (2d), but how can i prevent them overlapping?
i tried but where did i do wrong?
in this code, squares immediately gets destroyed and spawn new ones
i tried to decrease/increase the radius of overlapcircle
still nothing
did you debug to see what was running and what wasnt?
You would need to do like Physics2D.SyncTransforms() between each spawn if you want the new items to be visible to your queries
rn everythings running well
but like i said, for some reason overlapcircle works weird
ohhh wait i should have said this in first place
this is a 3d isometric game normally
but i made a new scene just for this
i even tried overlapsphere (adding them 3d box collider)
honestly i tried this but in a different way
it didn't worked
Guys, my line button.onClick.AddListener(ButtonClicked); will call the "ButtonClicked" function twice in a row when it's clicked, yet if I remove that line, the ButtonClicked function is not called at all. So if I was doubly binding it or calling it elsewhere, I'd see one call when I remove the line, not none. In fact I searched the entire solution for "ButtonClicked" just to make sure it's not being referenced elsewhere and it isn't.
Why is it getting called twice for one click?
Callstack shows it's coming from UnityEngine.UI both times
That may as well be 2 identical screenshots. But I'm getting 2 Debug.Log outputs from within ButtonClicked, and only one output from another event listener function on the same button.
For the same, single click
You'd have to show more code/context otherwise everything will just be guesses. My first guess would still be that you're registering it twice, maybe the method containing that line of code is called twice.
!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.
Searched entire solution, ButtonClicked isn't referred to in any other case
Actually
maybe the line that adds it is being called twice, I didn't check that, hang on...
I was never referring to ButtonClicked. I said the method containing the line of code
Code: https://gdl.space/ojifojubov.cs
I have an issue with a collider, when Instantiate an object and place it where my raycast hits I am getting collision issues with objects that are not square. I have a box collider on a prefab and on the long side the collision works fine, but when I rotate the object doesnt seem to collide from the small side, its almost like my box collider isnt rotating. I can get a video if needs be
That would be ButtonClicked 🙂
Related question - is there a way to print out how many event listeners onClick has registered to it?
(The Debug.Log statement int he previous screenshot is being called twice, it exists inside ButtonClicked)
@drowsy crest Any idea on my issue 🙏 ?
don't tag people not in conversation / actively helping w you #📖┃code-of-conduct
🫡 got it
Sorry sorry I see what you're saying now. "That line of code" referring to the line that registers it... and you were dead right... it's being called twice, my stupid fault. Thank you!
Yes sorry I was referring to the AddListener line
post video
have you looked at the collider with gizmos on to see whats happening there?
also take a screenshot when you turn it with the Physics Debugger , under Queries tab
I have in the past, let me re add a gizmos in
Is this what you wanted to see? 🤔
Ooooh that shows me a lot actually, let me get a screenshot
This is when its correct-
When its rotated 90deg -
And then a 45 degree angle -
So something must be wrong im just not sure what or how to fix it
seems the cast isnt rotating properly
Thats a really cool menu, any idea how to fix it?
oh you're using the bounds not the collider
esp when you rotate it angled, it fills the whole cube. Since bounds are that
Am i not using the collider bounds?
How would you go about doing it, or do you have a link youd recommend i look at
yeah instead of bounds use the size of collider
Collider[] colliders = Physics.OverlapBox(bounds.center, itemCollider.size, placementObject.transform.rotation, buildableLayer);
its half extents so you need /2 actually I think
Vector3 size = itemCollider.size;
Vector3 center = itemCollider.center;
Bounds bounds = new Bounds(placementObject.transform.TransformPoint(center), size);
Collider[] colliders = Physics.OverlapBox(bounds.center, bounds.extents, placementObject.transform.rotation, buildableLayer);
With a bit of fiddling and a hint of chatgpt i got this to work
What do you mean by "in a different way"? What other way is that?
chatgpt is not recommended due to the fact it will lead you astray most times, please !learn instead of using chatgpt
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
of course it can, but its a great tool as well. I come from web development side, i understand all the core concepts of programming just not the unity API and game dev world. Good questions and understanding what its spitting out can make chatgpt a VERY useful tool
well all chatgpt is, is a program that has access to the internet and pulls from websites and strings them together to get a answer. if your gonna use anything best suggestion is to look said thing up
So is OnCollisionEnter/OnTriggerEnter really that unreliable for complex MeshColliders in motion? I have a collision that works fine for BoxCollider, but MeshCollider doesn't register the event at all. I even set it to convex and tried continuous collision detection. Both objects have RB's (only 1 is kinematic), Colliders, and the physics layers are compatable
After a bunch of troubleshooting, the only answer I saw was Complex meshes can sometimes cause issues with collision detection. If you need precise collisions with a complex shape, consider simplifying the mesh or using a combination of MeshCollider and simpler colliders."
This is less of a problem and more of a curiosity,
I've got this ScriptableObject with some custom classes declared but the instances of them are null when the SO's OnEnable is called when I first make the asset. If their null at that point, when do they get initialized?
public class ScriptableAudioSetting : ScriptableSetting
{
public override List<ValueSetting> GetValues() => new List<ValueSetting> { Volume, DbMinMax, AudioMixer };
public ObjectSetting<AudioMixer> AudioMixer;
public FloatSetting Volume;
public Vector2Setting DbMinMax;
}
wait i might be dumb actually hm
it's actually that getvalues thats null
One simple solution is to calculate the position like you currently do, then add some small random shift to the result.
Another solution would be give a random delay before the bot can act on moving to the desired position, to simulate reaction time.
And of course can combine the two, adjust parameters to the shift/delay to make the difficulty adjustable.
Make it move more slowly
I think the second option would be the best. Could you help me to implement it?
Break it down into smaller parts and figure out each one.
im looking at the memory profiler and seeing graphics in there that arent in the game currently, anyone have an ideas how that happens..
Things are loaded into memory even if they are not rendered right now. For example, if something references them. Then there's also some engine resources that are used for various purposes.
Lastly, you should profile a build for most precise state of the memory, as in the editor there might be editor specific resources loaded as well.
If you need more precise answer, you should share some profiling data that you're looking at.
thank you very much, yeh im testing on an android build.. the only reference to it is a reference to an addressable that isnt loaded yet, so its difficult to know why its in memory
Either it's loaded via the addressables, or you reference it somewhere else. Or maybe even have it in a Resources folder.
What kind of a resource is it? A prefab?
theyre texture2Ds,
i can pin point when they turn up, but i cant see how or find any references in the scene, very strange
Im confused, my spherecast (non alloc) is returning the correct object but a point of zero (and a normal in the opposite direction im casting), looking online suggests its cause the origin starts inside an object, but even moving the origin outside doesnt change anything, also the cast ignores the layer of the object is "inside" and that object doesnt have a collider, so this shouldnt matter anyway - using hit.collider.ClosestPoint(transform.position) gives me exactly what I want hit.point to give me, it IS hitting the correct object, and returning the correct hit.collider just for some reason the hit.point is always zero and I dont understand why, for context this is the full line, any additional info to provide or any steps I can take to investigate further?
Physics.SphereCastNonAlloc(transform.position, 1f, Vector3.up, hit, 1f, listenLayers); (this line exists in a script that only has this line, attached to a default cube without a collider for testing)
Are you using the return value of SphereCastNonAlloc?
Im using the return value of hit (RaycastHit[]) but the return value of the cast itself is just a int which does return 1 (the correct object im hitting with the cast)
Actually
Notes: For colliders that overlap the sphere at the start of the sweep, RaycastHit.normal is set opposite to the direction of the sweep, RaycastHit.distance is set to zero, and the zero vector gets returned in RaycastHit.point. You might want to check whether this is the case in your particular query and perform additional queries to refine the result. Passing a zero radius results in undefined output and doesn't always behave the same as Physics.Raycast.
That’s likely applied to NonAlloc version as well
https://docs.unity3d.com/ScriptReference/Physics.SphereCastAll.html
So if im understanding this right, if my cast happens to start inside the cube I want to hit, then this is true? What if im testing from a million units away and then manually moving the cast (with a radius of 1) toward the cube in question? Surely it wouldnt be overlapping for the sweep at that point, unless I misunderstand what its saying?
If it overlaps on the starting point. I don’t get what you mean by “manually moving the cast”
The wireframe represents the exact pixels of the cast, when the inner circle turns red, and the cube turns green, there is a "intersection" and the NonAlloc result is 1, and the correct collider of this black cube is returned, and the point is zero - by "manually moving the cast" I mean just dragging it in the Scene view toward the black cube until there is a intersection - I also tested with the origin not inside the cube im moving, but maybe I dont understand when or how the sweep works
That’s what overlapping on starting point is. Sweep doesn’t care what happened in previous frame. It’s stateless query.
If collider detected within distance 1 from your transform.position then that’s gonna happen
Hmm, im not sure I fully understand? So if I wanted hit.point to return a non-zero value, the distance of 1 has to be larger than the transform.position or the collider im trying to detect needs to be further than a distance of 1 from the transform.position? (since 1 in this case, is the radius)
Yes, at the time you call SphereCast the collider needs to be further than 1
Hmm alright, ill play around with that and see if I can get some positive results - thanks for clarifying that up for me
guys I am trying to import a github project from another version of unity to new one 2022
and its showing only one error
these are the files
I have asked chatgpt but i know its not something wrong in the code
but something that can be due to the versions and it might be something you guys know
It is very obviously something wrong with the code
i mean its good working project that is not mine but a friends and its something to do with the version
No, you have a simple compile error
also i think like this maybe due to something to do with the version
what kinda error can i fix this without changing the version
The error message is telling you EXACTLY what the problem is
yea but i dont think problem could be in this code
wait
this is the file of the code
''' namespace TD.Inputs
{
public abstract class BaseInput
{
protected readonly Controls controls;
public BaseInput(bool enable)
{
controls = new Controls();
if (enable)
{
controls.Enable();
}
}
public void SetActive(bool active)
{
if (active)
{
controls.Enable();
}
else
{
controls.Disable();
}
}
public void Dispose() => controls.Dispose();
}
} '''
sorry how do i make this code come under a snippet in discord
!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.
use a paste site
!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.
also the controls script
There you go, they are in 2 different namespaces
what can i do to fix this
also how did this happen cause
the other person had this project running
are you modding a project or something?
do you not know how to add a namespace to a script?
So i am trying to learn the UI inputs that the project had implemented
No honestly
do you know what a using statement is?
yes i do know it
then that is what you need to add
in the baseinput file?
using namespace bginputs?
so you don't know how to use a using statem,ent
yea i know in general terms
like using a library
or using the general inputs
symstems
using BG.Inputs;
i just add those things
wow
it worked
wth
chatgpt was showing me lots of things
like reimporting and stuff like that
i want to ask one more thing
how did this could have happend?
you really need to go and learn some C# basics before continuing
yea i feel this too
did you regenerate the Controls class?
no i did not do anything
just downloaded the project
show me the link to the github
and imported
it again
i think
its cause of the importing
this is the link
this guys is amazing i know him
but didnt want to ask more from him
about this stuff
you changed something
namespace TD.Inputs
{
public partial class @Controls: IInputActionCollection2, IDisposable
i did not i guess
but how do you know from this
code?
Look at the namespace. I copied from the original on Git
nope
the code does not lie
😅
i know but here
i think this controls thing is a culprit
or something
also the script says it changes
Yes, if YOU regenerate, Unity does not do that automatically
i feel still
cause i just downloaded it
these files are one of the culprits
😄
also will i approach it as like changing the namespace name in the controls script to tg.inputs
instead of adding a using namespace
in the baseinput.cs
I wouldnt do becuase if you regenerate it will change it back to BG
I'm trying to make a monobehavior whose sole purpose is to display a text box in the inspector for use as documentation. Is there a way to prevent it from being added to builds?
what the heck
#if UNITY_EDITOR
public class Note : MonoBehaviour
{
[TextAreaAttribute(3,10)]
public string Notes;
}
#endif
``` Here's what I have so far. This seems like it'd throw an error if I tried building, although I haven't tested it yet
look at this. You changed something
i promise from the heart
but yea i feel i would have done something
why do this? Just put the script into an Editor folder
but i for sure to hell didnt do a typo
Since the script is now in the editor folder, it can't be placed in the inspector
unlucky
the use case is pretty weird. having documentation in the game objects does not sound good. there is the tooltip attribute https://docs.unity3d.com/ScriptReference/TooltipAttribute.html but if you're trying to make documentation,
either make some asset and make it pretty with an editor script
or use some other tool like even a pdf document
Learn something new every day.
In that case just wrap the declarations in the #if and Leave an empty class for the compiler
thanks for the explanation. I just wanted a quick and dirty way to have notes for myself
I'm going to go with this
I am somewhat surprised at this, it's a very specific error message so Unity have obviously put some thought into it but I cannot think for the life of me why they would have such a restriction
I imagine it would be due to the high odds of missing components ending up in builds
I'm thinking this may be a legacy thing dating back to the early days
Surely the build would just fail if the class was referenced, just like with any UnityEditor API usage
does anyone know of a tutorial or already existing asset for a nested tooltip system like in ck3/bg3?
i'm trying to create one but the behaviour is so complicated with when to hide and show them when the mouse enters and exits them
be careful with this, putting serialized fields inside an #if UNITY_EDITOR can cause serialization errors and weird problems in builds, there's a specific error you'll see about this sometimes! not sure if it would affect you in this situation but it's worth being aware of just in case
I'm making a track with sprite shape and I'd like to be able to access the Sprite shape spline from code so I can use it like a rail, is that possible?
anyone mind linking me to a tutorial on how to make an interactive world space ui? every answer ive found online is either vague or untrustworthy
Looking at BG3, it seems that the nested tooltips show when you hover over something that should produce a tooltip inside of a existing tooltip (like an item that has a tooltip to a spell), it seems you press a key to keep the first tooltip open, then when you hover over something in that tooltip, it produces a second nested tooltip, when you move away from that "something" while still in the original tooltip, the nested one goes away - certainly sounds like a very confusing system that will probably involve playing with sort order and generating prefabs a lot, is your issue with detecting the text that should create the second tooltip? And are you using TextMeshPro for that or another system?
i've looked into using procedurally generated TMP links and it seems feasible, the problem i ran into was the behaviour: (based on ck3 more so than bg3)
hovering over something that should spawn a tooltip should do so, though it shouldn't spawn the same tooltip again from the same source
the cursor exiting the original trigger for the tooltip should hide the tooltip, but not if the cursor goes into the tooltip
if the cursor leaves the original trigger and onto the tooltip and then back to the original trigger it shouldn't hide the tooltip
if the cursor leaves the tooltip to go to a nested tooltip it shouldn't hide the original tooltip
if the cursor leaves the nested tooltip, it shouldn't hide the original tooltip unless the cursor is outside the original tooltip
there's so much to it, i was able to get most of this working well but then one thing wouldn't work and i'd have to rewrite over and over again
the bg3 approach would be easier because it uses a button to spawn the tooltip and you have to click out of the tooltip instead of being based on cursor position
might go with that instead
Hi all, looks like the syntex highlighting in my vscode code isn't working properly? Does anyone know a fix or encountered similar? Not sure why the majority of the lines after
float alteredDamage = 0;
is white out
because they are inscope variable ?
ohh is that why? I just switched from visual studio to vs code
if that's intended behaviour then Im happy with that haha just not sure if I did something wrong
Also, an advice for managing stats. Try to keep track of where your stats are coming. Instead of using a float for your max health, you might want to use a collection of object that represent the source of your stats. (You can easily cache the result)
Ive been thinking about improving the way Im keeping the stats. can you explain a bit more on what you mean?
public class Stats : MonoBehaviour
{
[Header("Character Base Stats")]
[SerializeField] private float _maxHealth;
[SerializeField, ReadOnly] private float _curHealth;
public float MaxHealth
{
get => _maxHealth;
set => _maxHealth = Mathf.Round(value * 10f) / 10f;
}
[ReadOnly] public float CurHealth
{
get => _curHealth;
set => _curHealth = Mathf.Round(value * 10f) / 10f;
}
[SerializeField] internal float Armour;
[ShowInInspector, ReadOnly] internal float BlockChance = 0;
internal bool IsDead() => CurHealth <= 0;
[Header("Attack Base Stats")]
[SerializeField] internal float AttackDamage;
[SerializeField] internal float AttackSpeed;
[SerializeField, ReadOnly] internal float CritRate;
[SerializeField, ReadOnly] internal float CritDamage = 1.5f;
[Header("Body Class")]
[SerializeField] internal Class Class;
private void Start()
{
CurHealth = MaxHealth;
}
}
Right now I have just one script that holds the stats for each of the character
Instead of doing maxHealth += X;
You do maxHealth.Add(new MyStructThatRepresentTheSource(X))
and the reason for doing it this way is to better keep track of where the stat change comes from?
Oh, really bad idea to modified the serializedfield.
It will help you down the line to make more complex behavior.
Obviously, if you want that.
Things like increase MaxHealth Gain by BloodStone by 50%.
it sounds cool, but sorry I dont think Im understanding the Struct thingy
Or things like Reduce MaxHealth by X for 5s.
I was thinking to do like a
[SerializeField] private float maxHealth;
public float MaxHealth => maxHealth;
...
public void AddHealth();
something like this, does this avoid the issue?
private class Stat
{
private List<StatModifier> modifiers = new List<StatModifier>();
private float current;
public void Add(StatModifier statModifier)
{
modifiers.Add(modifier);
Refresh();
}
public void Remove(StatModifier statModifier)
{
modifiers.Remove(statModifier)
Refresh();
}
public void Refresh()
{
current = modifiers.Sum(x => x.Value);
}
public float GetValue()
{
return current;
}
}
public class StatHolder : MonoBehavior
{
[SerializeField] private float maxHealth;
public Stat MaxHealth {get; private set;}
private void Awake()
{
MaxHealth = new Stat();
MaxHealth.Add(new StatModifier(maxHealth));
}
}
It really is not necessary, but I find it way easier to implement complex feature when working this way.
ahhh I see
Also, StatModifier could be a really generic thing. Personally, I'm not using stat only but every form of "Modifier".
then after a few rounds or a few modifiers, you can simply look at the List and track what has changed
more like what caused the change etc
Yeah
and you can have a IEnumrator to remove a modifier thus the reduce X for 5s
Or make complex behavior that depends on that.
I see I see, this is super cool haha
but then I'll have to rewrite the whole thing.... HMMMMMMM
If you did not anticipate such feature, you might want to keep what you want for your current project.
If you face a wall, knows that there is way to get around it.
I was a bit annoyed at the way I did the health etc, it's like reading and overwriting a public value
was not a big fan of it
It works for simple game though.
in this case, the StatModifier can be a simple class that returns a value right?
public class StatModifier
{
public float Value { get; private set; }
public StatModifier(float value)
{
Value = value;
}
}
Yes, eventually you might want to use polymorphism to increase the feature of each individual one.
yep that makes sense, so almost makes sense to pass an interface as a modifier
Yeah, an interface could work as well but in this case a base class is stronger.
Given that you do not want to have complex object in your list.
You would want to have people sending object with lifecycle that you do not control.
Your !ide is not properly configured. Configure it
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
• :question: Other/None
When you did that it will properly inform you of the invalid syntax you wrote
weird, I did all the steps
Im currently using the preview unity 6, but the visual studio package is updated, should be fine?
question: would you lump every regular stat (max health, current health, attack speed, crit) etc into the StatHolder? More specifically current Health might not particular work with this structure? It might be better off just a float by itself? If that makes sense? Appologies Im still trying to wrap my head around this, it seems very useful
I usually only have a float for things like that. You could potentially have a variate of a statistic that combine a max value and current value together.
public class ModifiableStat
{
public float Value { get; private set; }
public Stat MaxValue { get; }
public void Modify(float value)
{
Value = value;
Value = Mathf.Clamp(Value, 0, MaxValue.GetValue());
}
}
...
public ModifiableStat Health = new ModifiableStat();
public Stat MaxHealth => Health.MaxValue;
ahhh cool cool
Thanks, I think this really helped me understand just general usage of classes hahaha
For an idle animation in a FPS, where I don't need to necesarry have the character sway around and just the camera, is it a better approach to make animator component and animation clip or to make it in code by altering the cam localRotation/position dirrectly? I do have some camera animations I want to add, idle, landing, jumping, crouching, mostly just changing the rotation to create an impact of some sort.
Ideally, you wouldnt want to animate the camera directly. I suggest you use Cinemachine and animate a virtual camera and then from code decide what you want to follow. I also believe you can have something like a blend between two virtual camera.
public enum StatModifierType
{
Flat,
Percentage
}
public class StatModifier : MonoBehaviour
{
public float Value { get; private set; }
public StatModifierType ModifierType { get; private set; }
public StatModifier(float value, StatModifierType modifierType)
{
Value = value;
ModifierType = modifierType;
}
}
public class Stat : MonoBehaviour
{
private List<StatModifier> modifiers = new List<StatModifier>();
private float baseValue;
private float current;
public Stat(float baseValue)
{
this.baseValue = baseValue;
Refresh();
}
public void Add(StatModifier statModifier)
{
modifiers.Add(statModifier);
Refresh();
}
public void Remove(StatModifier statModifier)
{
modifiers.Remove(statModifier);
Refresh();
}
public void Refresh()
{
float flatSum = 0f;
float percentageSum = 0f;
foreach (var modifier in modifiers)
{
if (modifier.ModifierType == StatModifierType.Flat)
{
flatSum += modifier.Value;
}
else if (modifier.ModifierType == StatModifierType.Percentage)
{
percentageSum += modifier.Value;
}
}
current = (baseValue + flatSum) * (1 + percentageSum);
}
public float GetValue()
{
return current;
}
}
Here's what I ended up with, I now have way more control of each stat, very cool honestly hahaha
Hello, I made a world space UI but i can't interact with it at all. Anybody know how to fix it, I would greatly appreciate it, thanks!
screenshot your hierarchy
Doesn't sound like a code problem. #📲┃ui-ux
oh, my bad i just saw a lot of fixes were with coding for debugging raycast
Helped this person yesterday - maybe you have the same problem?
#📲┃ui-ux message
I am following this tutorial by CLC but when I add PerObjectData.ReflectionProbes my editor immediately crashes. I fixed the crashing by also adding PerObjectData.ReflectionProbeData (it was not in the original tutorial) but the reflection probes seem to not be sampled correctly and is uniformly grey. Anyone else have this issue?
you might have more luck asking in #archived-lighting perhaps? #archived-shaders maybe but I dunno
I have a very weird problem. The animation rig sometimes become invisible at a certain angle. Animator is however set as Always animate ( in case it would believe it's not on the screen)... anyone had this issue? it's driving me insane
thats a 2k bone setup
Is there any way for a non-MonoBehaviour class to check when it is serialized in the inspector. Or, perhaps, check when this class is added as a List item, since Unity doesn't call its empty constructor, which is my goal
OnValidate()?
Reset()?
What are you trying to do
"added as a list item" doesn't actually affect the thing at all
Unity doesn't call the item's empty constructor when adding it, and I'm trying to call it
Why would it? It's not being created
Constructors run when an object in C# is created
Oh wait a non-monobehavior?
The item is added to the list via inspector
Yes
I misread
You can use a custom editor for the thing with the list
To detect when adding a thing to the list
Yeah, it's not like I cannot track it in the original class
Since it has ExecuteAlways, I can track it in Update too
I just want to find a way to make the class "trackable" without the additional functionality in its MonoBehaviour holder
I have discovered ISerializationCallbackReceiver, but it doesn't work for my use case
What's the end goal here
The list item is added with everything set the its Type's default. I want to assign the default variables myself
The default list add actually clones the last entry if it exists
I don't think you can really change that without a custom editor
You could also do a quick workaround like using a button attribute like this and implement your custom "add elements to the list" logic there: https://dbrizov.github.io/na-docs/attributes/drawer_attributes/button.html
The worst thing here is cloning the reference-type entry
Thank you for your help, I'll consider using the custom editor then
I'm running into some issues, with this first person controller. It's...allowing me to move the camera up and down, but not any other direction. Additionally, it's not allowing me to move at all, and I'm not sure what I did wrong with it.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Thank you, posted in one of those services.
https://paste.ofcode.org/ktXcxdPkF36gDuyEAAzpPk
is the camera child of the player?
Oh, I'm so dumb. I thought I had a serious problem, that was precisely it. Thank you.
is there a way that I can view a materials offset in editor without actually applying changes?
i have a script that modifies the material offsets at editor time via a script that uses ExecuteInEditMode, but the script ends up modifying the offsets of the material
Couldnt you just create a new material using the constructor? Make an instance of it, like unity does at runtime when you try to edit at runtime
You should be able to call Destroy on it when you're done with it
Or just actually create a new material asset and use it temporarily for your editor uses
so id probably have to destroy it right before i hit play or something then too?
Id ideally destroy it as soon as you know you dont need it. Guess it depends what you're actually using it for, because im not really sure why you want one in editor that doesnt actually apply to the asset.
Also iirc you should be destroying materials allocated at runtime too which could be created by accessing .material
how do I call a void in a different script that has its own variable?
like i wanna call this
public void Missile1UI(float time1)
this is what im doing to call it
gameObject.GetComponent<HUD_ctrl>().Missile1UI();
if I DONT add the "float time1"
i get this error:
Severity Code Description Project File Line Suppression State
Error (active) CS7036 There is no argument given that corresponds to the required parameter 'time1' of 'HUD_ctrl.Missile1UI(float)' Assembly-CSharp C:\Users\censored\Downloads\Ace combat fangame\Assets\Scripts\Weapon_System.cs 53
if I DO ADD IT, i get these 3 errors
Severity Code Description Project File Line Suppression State
Error (active) CS0103 The name 'time1' does not exist in the current context Assembly-CSharp C:\Users\censored\Downloads\Ace combat fangame\Assets\Scripts\Weapon_System.cs 53
Error (active) CS1003 Syntax error, ',' expected Assembly-CSharp C:\Users\censored\Downloads\Ace combat fangame\Assets\Scripts\Weapon_System.cs 53
Error (active) CS1525 Invalid expression term 'float' Assembly-CSharp C:\Users\censored\Downloads\Ace combat fangame\Assets\Scripts\Weapon_System.cs 53
since the Missle1UI function requires a float (time1), you need to pass it a float.
Like this:
float timeParameter = 1f;
gameObject.GetComponent<HUD_ctrl>().Missle1UI(timeParameter);
(though I have no idea what that parameter actually does, so not sure what value to pass in and randomly chose 1f)
#💻┃code-beginner
they're called methods not a "void"
also post code properly its hard to read on mobile
like this?
Error (active) CS0103 The name 'time1' does not exist in the current context Assembly-CSharp C:\Users\censored\Downloads\Ace combat fangame\Assets\Scripts\Weapon_System.cs 53
Error (active) CS1003 Syntax error, ',' expected Assembly-CSharp C:\Users\censored\Downloads\Ace combat fangame\Assets\Scripts\Weapon_System.cs 53
Error (active) CS1525 Invalid expression term 'float' Assembly-CSharp C:\Users\censored\Downloads\Ace combat fangame\Assets\Scripts\Weapon_System.cs 53```
btw these are errors, not code
i meant show the script the error was telling you about
but yeah you need to configure your IDE these are very basic c# errors
looks like you're trying to call it with the word 'float' in the parameter list. You don't need to do that. It knows it's a float from the method definitoin
they got fixed now
alr well if you haven't , you should still be configuring your IDE. Then would look at the pins in #💻┃code-beginner
i had mine configured a long time ago, but this is a new laptop, so it might not be configured anymore
you should redo it then because coding without a configured IDE is a good way to shoot yourself in the foot esp as beginner , syntax , spelling errors etc..
i think it might be configured (im using VS 2022 and I downloaded the unity options, went into preferences and selected it as my preferred script opener)
did it underline the errors you shown above in the editor ?
it can autocomplete getcomponent statements, if that means its configured
alr then
as long as red underlines show up and the other c# objects like unity ones
I used to be so much better at unity, but I forgot alot
the error was c# specific not unity
good to do a crashcourse on c# .
Btw a void is a return value for a function/method. It means it doesn't return any value
private void Sleep()```
[access modifier] [return type] [method name] [parameters]
if I have a list of triangles with their UVs
and I have a list of emission textures that those triangles index into
and I am inside an async task
is there any good way to actually see if the space on the texture covered by the triangles is actually emissive?
Currently I have to, out of the task, convert all the emission textures to read/write texture2d's, and then do getpixels on them and store that in a massive buffer(which is horrid for RAM), and then in the task i can "sample" those emission textures for each triangle(all so I can disacrd triangles that are not actually emissive, aka if the space they cover on the texture is black)
This works, but can use HUGE amounts of ram, is there a better way given that you cant dispatch compute shaders from inside an async task?(the triangles created inside the task, and the code that needs that trimmed triangle list is also inside the task)
Is the emission texture only on the GPU normally?
yeah
Each triangle has just a single UV coordinate, instead of for each of the three vertices?
And a texture index for which emission texture it uses?
3, one for each vertex
Okay, so you need to know if any of the pixels the triangle covers is emissive? And the triangles can be any size, covering any number of pixels?
or texels, rather
yeah
I need a better way than my current method which uses too much memory(store all the textures into an array of arrays and sample from that per-triangle) that can run inside an async task, aka off main thread
Is your current method also figuring out all the texels that are covered, or half covered, by the triangle and checking each one? Does the center of the pixel have to be within the triangle to count or just any overlap?
That bit seems like the most complicated, whether it's implemented in CPU or compute shader
doesnt really matter, its aproximate, I think I am only actually checking the UVs directly covered by each vertex and the center of the triangle rn
Okay, I had eliminated this idea because I thought it needed to be exact, but you could be sampling a lower resolution mip map instead of the whole texture and drastically reduce memory usage. This could apply to your current implementation, or also in a compute shader or something.
If you can do this in a compute shader, you could use the area of the triangle to choose the mip level, to save on how many samples you need to do to get a rough average of a larger area.
but I need to make sure the textures are rw/write enabled so I gotta set them to the active rendertexture then do readpixels from that back into a read/write texture
and you cant call compute shaders inside async tasks
You could use AsyncGPUReadback to read back a specific mip level of a texture directly to a NativeArray.
For dispatching compute shaders inside async tasks, you could implement a thread-safe queue which the main thread checks periodically.
UniTask also has await UniTask.SwitchToMainThread(), if that is at all an option.
If you're using Unity 2023.1+, you can also use Awaitable, which has await Awaitable.MainThreadAsync();
Extremely simple kill/respawn script here, with the aim being that you respawn at the last touched point once you hit the mesh collider with the Hazard tag. I've made sure that the hazard had the right tag, and even is set to isTrigger, so I'm not sure what I'm missing.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KillRespawn : MonoBehaviour
{
//Variable for the last respawn point the player has touched.
Transform lastRespawnPoint;
//This is going to trigger on the entering of a given respawn point, once touched and once they die.
private void OnTriggerEnter(Collider collision)
{
if (collision.gameObject.CompareTag("Hazard"))
{
transform.position = lastRespawnPoint.position;
}
//When you touch a respawn point, it saves your current progress to that one.
if (collision.gameObject.CompareTag("Respawn"))
{
lastRespawnPoint = collision.gameObject.transform;
}
}
}
You could start by explaining what's going wrong.
Oh, sorry. I guess it's not doing what I aimed for it to. Specifically, not respawning the player back to the respawn points that get touched.
Well, is the code actually running? You should take some basic debugging steps, like adding some logs, and printing the tags and names of the object(s) your code detects, etc.
I threw in a Debug.Log at the If for the hazard statement, and it triggered, so that's working.
I recommend adding a basic one outside of all the if statements like:
Debug.Log($"Collided with {collision.collider.name} with tag {collision.collider.tag}");```
and then one inside each if statement
Just putting that in gives me a ton of errors, so not sure.
what errors
"a ton of errors" is vague and not actionable
most likely it's just a simple syntax problem, or you put it in the wrong place.
That's probably true.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KillRespawn : MonoBehaviour
{
//Variable for the last respawn point the player has touched.
Transform lastRespawnPoint;
//This is going to trigger on the entering of a given respawn point, once touched and once they die.
Debug.Log($"Collided with {collision.collider.name} with tag {collision.collider.tag}");
private void OnTriggerEnter(Collider collision)
{
if (collision.gameObject.CompareTag("Hazard"))
{
Debug.Log("DEATH");
Debug.Log($"Collided with {collision.collider.name} with tag {collision.collider.tag}");
transform.position = lastRespawnPoint.position;
}
//When you touch a respawn point, it saves your current progress to that one.
if (collision.gameObject.CompareTag("Respawn"))
{
lastRespawnPoint = collision.gameObject.transform;
Debug.Log($"Collided with {collision.collider.name} with tag {collision.collider.tag}");
}
}
}
HEre's the errors.
you put the code outside the method...?
Why
naturally I meant to put it inside the method...
I said outside the if statements
i.e., on the first line of the method.
what you wrote isn't valid code, so yeah you're getting a bunch of errors 😉
I'm confused by what you mean by putting it inside the method.
do you know what a method is?
would it help if I used the term function?
This is your method:
private void OnTriggerEnter(Collider collision)
{
if (collision.gameObject.CompareTag("Hazard"))
{
Debug.Log("DEATH");
Debug.Log($"Collided with {collision.collider.name} with tag {collision.collider.tag}");
transform.position = lastRespawnPoint.position;
}
//When you touch a respawn point, it saves your current progress to that one.
if (collision.gameObject.CompareTag("Respawn"))
{
lastRespawnPoint = collision.gameObject.transform;
Debug.Log($"Collided with {collision.collider.name} with tag {collision.collider.tag}");
}
}```
anything outside of this
is outside the method
you put it on the line above this
aka, you put it outside the method
the { } enclose the body of the method
all the code in your method needs to go between those { }
so what I meant was to put it on the first line inside the { }
Ah. I still get quite a few errors, though.
public class KillRespawn : MonoBehaviour
{
//Variable for the last respawn point the player has touched.
Transform lastRespawnPoint;
//This is going to trigger on the entering of a given respawn point, once touched and once they die.
private void OnTriggerEnter(Collider collision)
{
Debug.Log($"Collided with {collision.collider.name} with tag {collision.collider.tag}");
if (collision.gameObject.CompareTag("Hazard"))
{
Debug.Log("DEATH");
Debug.Log($"Collided with {collision.collider.name} with tag {collision.collider.tag}");
transform.position = lastRespawnPoint.position;
}
//When you touch a respawn point, it saves your current progress to that one.
if (collision.gameObject.CompareTag("Respawn"))
{
Debug.Log($"Collided with {collision.collider.name} with tag {collision.collider.tag}");
lastRespawnPoint = collision.gameObject.transform;
}
}
}```
if I'm doing this right.
ok now this is right and it's my mistake
the problem is you confused me by using the name collision for your variable
it made me thing it was a Collision, which you get in OnCollisionEnter
since you directly have a Collider you can do this:
Debug.Log($"Collided with {collision.name} with tag {collision.tag}");```
but I would recommend naming your variable better. Something like "other" or "otherCollider"
Usually people do Collider collision because they changed from OnCollisionEnter to OnTriggerEnter and didn't bother changing the name of the parameter
Alright. No errors, I'm going to walk into the hazard's box collider and see if it triggers.
I'm definitely colliding with the Hazard tag, so the real question is why it isn't teleporting me back to the transform for the respawn.
Well is the log you put inside the Respawn if statemtn running? Instead of duplicating the log line in each if statement you should put a different log there, like cs if (collision.gameObject.CompareTag("Respawn")) { Debug.Log("Respawn entered"); lastRespawnPoint = collision.gameObject.transform; }
or sorry
i see you have a DEATH log already
is that logging or not?
It was when I tested it originally
Oh, it still is.
ok it is
The respawn one too.
So the code is working.
My guess then is that you are using a CharacterController
Okay. Time to figure out how to integrate this. I...don't think it needs to go into my script for my player controller, but I may be wrong.
whats a simple way to assert Dispose() from IDisposable is called before GC cleans up a class just to make sure i don't forget to call it
as project gets bigger its easy to forget these things
Maybe something like...
bool wasDisposed = false;
public void Dispose() {
// cleanup
wasDisposed = true;
}
~MyClass() {
if (!wasDisposed) throw new Exception("Forgot to dispose me!");
}```
yeh but i dont think the dtor will get called if another class references it still of which the dispose function was to clean up references
Well you asked about GC
it's not going to get GCed until those refs are released either
hm fair point
I have a coroutine:
private IEnumerator DoCornerHint() { ... }
and in the same file in a called function I have:
StartCoroutine(DoCornerHint());
but during runtime I get:
Parameter name: obj```
even though `obj` is an overloaded parameter and `DoCornerHint` takes no parameter... I've never had this issue ever...
Share the error details.
Can you show the full error/code?
Parameter name: obj
UnityEngine.Bindings.ThrowHelper.ThrowArgumentNullException (System.Object obj, System.String parameterName) (at <5580a85131d6485c8bcaf178996ed0c0>:0)
UnityEngine.MonoBehaviour.IsObjectMonoBehaviour (UnityEngine.Object obj) (at <5580a85131d6485c8bcaf178996ed0c0>:0)
UnityEngine.MonoBehaviour.StartCoroutine (System.Collections.IEnumerator routine) (at <5580a85131d6485c8bcaf178996ed0c0>:0)
Globals.Interface.ShowCornerHint (System.String Text) (at Assets/Globals.cs:67)
CameraController.Update () (at Assets/CameraController.cs:17)
Share the Globals.cs !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.
One thing that I'd avoid doing(even though it is probably fine in the latest versions) is putting several MonoBehaviour in one script.
This could potentially be the cause of the issue
Another thing is, I'd avoid starting coroutines via string name.
it was a test cuz i tried multiple ways of starting the coroutine
Other than these 2 things I can't see anything that could cause a problem.
Reccomendation: Don't use the string version of StartCoroutine
we just talked about this
Though, the line numbers in the error don't match the code...
i noticed as well and i restarted and it gave a different line
Parameter name: obj
UnityEngine.Bindings.ThrowHelper.ThrowArgumentNullException (System.Object obj, System.String parameterName) (at <5580a85131d6485c8bcaf178996ed0c0>:0)
UnityEngine.MonoBehaviour.IsObjectMonoBehaviour (UnityEngine.Object obj) (at <5580a85131d6485c8bcaf178996ed0c0>:0)
UnityEngine.MonoBehaviour.StartCoroutine (System.Collections.IEnumerator routine) (at <5580a85131d6485c8bcaf178996ed0c0>:0)
Globals.Interface.ShowCornerHint (System.String Text) (at Assets/Globals.cs:52)
CameraController.Update () (at Assets/CameraController.cs:17)
not much help though
I bet it has to do with multiple MonoBehaviour in one file, but maybe I'm wrong.
Yeah definitely one MB per file
the other thing that could be going wrong here is something along the lines of:
- Starting a coroutine on a destroyed object
- Starting a coroutine on a deactivated object
- Starting a coroutine on a prefab
Showing the CameraController script might help too
I think it's almost definitely the destroyed object thing
nah its used on the event system which is never deleted
To avoid ambiguity, i've decided to start using namespaces more. However, I'm not sure about using monobehaviours inside a namespace. I looked it up and people say it sometimes works and it sometimes doesn't, which isn't reassuring. I'm open to new ways to battle class name ambiguity though (I'm thinking of Prefixing my class names but I'm not sure if that's good practice...)
There's no relation between namespaces and MonoBehaviour whatsoever. MonoBehaviour is just a base class.
oh not MonoBehaviour in itself, like any class that implements it
I'm not sure what you mean, but there shouldn't be any problem. Feel free to use namespaces as much as you like.
Is it possible to find the outline of a sprite as a vector array (or similar) I want to get the world space coordinates of the sprites outlines
There is a way on dedicated server to create a command system ? I cant type anything in the console 😅
Anyone know a solution about that ?
Doubt it. Outlines are usually generated with shaders.
Maybe outline is the wrong word here. I mean more like an array of vectors that if connected by a line "outline" the sprite.
I don't recall such a feature. I think it would be quite expensive performance-wise. Although you could generate such outlines as assets from scratch and then just load them instead of generating those in the runtime.
You probably can find a hack to change this online. Alternative solutions are to spawn a new console window or adding support for remote consoles through a network socket, allowing you to also send commands remotely.
I don't understand why this is not supported natively 😬 But thanks for your answer !
Tbf, commands aren't a feature in Unity at all, so there isn't really a place to pipe this input by default.
is there a way to simplify this expression?
return RootTransform == null ? transform : RootTransform;
You can remove the == null or maybe do return RootTransform ?? transform (not sure if that works well though, probably doesn’t)
you want to simplify a syntax which is, in itself, already a simplification?
yeah I tried the latter already
If you are using the == null check to check for truly null/unassigned variable, it's safe to use the ?? operator to shorten it to:
return RootTransform ?? transform;
but if RootTransform is destroyed or it's a serialized field with an unassigned reference, it will not truly be null, so it will pass the check.
There are operators adjacent to this expression which simplifies these things such as ?? so I don't think it's that outlandish
Okay that was my problem then, it was a serialized field. Thanks!
you should not even be going there when it comes to Unity Objects
Fake null objects being created for serialized fields (and for GetComponent) is only done in the editor to provide more detailed exceptions, like UnassignedReferenceException and MissingReferenceException instead of NullReferenceException, but is not done in builds.
But destroyed objects not being truly null holds true for both editor and builds.
Is there any easy/sensible way to profile build times, particularly looking at shader variants? Or will it be a case of digging through build logs
What would you expect to find out via profiling in regard to shader variants?
The compile time of each in an easily accessible way, so that I can fix the seemingly numerous ones that contribute to my current fairly ridiculous 24 minute cold-build time
you fix shader variants by reducing the material variants that use the shader with different features enabled
profiling would not meaningfully help with that. the problem isnt shader complexity, its the number of variations of the same thing that needs to be recompiled with tiny differences.
I am aware of how to reduce shader variants, my question related to finding an easy way to find which shaders to reduce variants of in order to optimise build time
how many shaders are you using in your project? normally you should be aware which are used a lot in many variations from working with the project.
I can guarantee that about 90% of the variations Unity is compiling are not being used in my project, they're just being compiled as shader features that I will want to disable
I keep running into the same problem. I have a dynamic scene loader, when the player enters some trigger more of the level loads in. I have a problem dealing with scene defined items or characters in my save system (which is based on serializing as strings and player prefs). If a player moves an item to a different scene, or a character ends up in a different scene, how do I load that from my save file? How should I approach instantiating serialized objects?
My save system deals with this by basically tagging each saved thing with a 'path' which includes which scene it was saved in. In my case, I never have sequential scenes so it's an easy "Check if the scene path matches current, if so, load, if not, don't load"
As for instantiating serialized objects, the main thing is to keep static data related to the object separate from any dynamic data.
For inventory loading, I used a kind of database (loose term, not an actual db) that holds a reference to all possible item prefabs, then all the load system does is asks the item database what item it should load in based on the unique identifier saved upon serialization.
I was thinking something similar is the way. So storing a mapping of a name/path to a prefab in something like a scriptable object asset? I wonder if this is what "Assets/Resources" folder is for? So if all item prefabs would be stored in there they could be simply instantiated/ loaded via a string path? (In my only game so far, I only used resources for loading music tracks)
The SO itself only would have a direct GameObject reference (in a database-esque structure where you can query what prefab matches what saved unique id) - that way you never need to worry about where the prefab is stored in your project folders/never need to worry about resources.
Resources.Load is a pretty old and limited way to do things.
(I don't mean to prematurily optimize - just for the sake of understanding things: Resources.Load still allows Unity to manage what's actually "loaded", while having a scriptable object somewhere referencing all items is identical to loading all the prefabs in the scene - just not instantiated?
I can't answer that for certain but I would be very surprised if a single list of prefabs would have any noticeable impact on any modern platform
It would have impact on the memory consumed. Unity has to load everything referenced in the scene. If it means a list of prefabs, then they would be loaded as well, along with all the models, textures and other data they're referencing.
Sure, but Resources.Load is still probably the worst when it comes to memory consumed + loading, directly from Unity itself
https://learn.unity.com/tutorial/assets-resources-and-assetbundles#
if you need to manage memory in that way, you should use adressables instead of Resource.Load however, Resource.Load has very little utility for memory management
considering we're likely talking about small-ish games here, i'd ideally design and scope my game in a way that i can load all of it into memory and never worry about managing what is loaded, outside maybe terrains and other extremely heavy data.
Yep, it's important not to overengineer your project and avoid premature optimizations.
heuristically a game that needs resource-streaming is unrealistic without a > 7-figure budget anyway.
I don't know if i'm posting in the correct room, but is there a way to remove the window border from a build?
not sure if i'm using the correct term here
Could you post a screenshot of it?
alright thanks
How the C# library hasn't wrapped up a way to make the game borderless is astonishing
meh. Unity has much bigger fish to fry. I can see how it hasn't been prioritized.
- It's not that common of a use-case
- It has well known and simple workarounds you can find with a simple google search
lol, the C# libraries have, it's just that Unity doesn't implement them because of cross platform compatibility issues
Not the built in C# library I meant
Making the game borderless is not a common case? Almost every game has that option, unless the guy asking the question meant something else because I wasn't following
prob apple is a pain to work with
Borderless Windowed is very common but in fullscreen mode. Fullscreen Borderless Window
That depends what you mean by built in. Mono doesn';t implement OS specific things because it is a cross platform library set
borderless windowed mode without being fullscreen is less common
and without a title bar
how would you even move it without titlebar 🤔
You're confusing the CLR runtime with C# Unity API
I see. So there's a built in option in full screen mode
yes - full screen borderless window is built in
no, you are displaying a lack of knowledge
Wait yeah...
No I am not, you're saying the C# API can't implement platform specific code because it is run on the Mono runtime
That is not what I said at all
Then care to elaborate what this means: Mono doesn';t implement OS specific things because it is a cross platform library set
I guess the guy who asked the question wanted to make his own border in non full screen mode
It's very simple. In the very nature of cross platform systems they CANNOT include any OS specific actions at compile time because if they did the resulting code would no longer be cross platform
A compile time #IF conditional can do what you're talking about.
Either way that wasn't my point in the first place
The Unity C# API can obviously figure out what OS it is running on at run time. Which is what I originally said until your brought up the Mono runtime which is of no relevance
you are talking about conditional compilation which is a completely different animal than a dll which is cross platform compatible
What does any of that have to do with the Unity .NET API implementing platform specific code?
Everything, Unity's API can only work with what it's been given. The Mono .Net libraries are platform agnostic and therefore Unitys code has to be as well
Unity can do whatever they want, they can build platform specific libraries or part of the API on top of mono, there is nothing stopping them. Mono is just a library they use to base parts of the engine. There are already parts of the API that are totally platform specific, and they could do the same thing for this scenario (Ie, add a new class for windows specific windowing functions like hiding the title bar)
However I think there is some misunderstanding somewhere here between you two causing this
I don't think you're following. The topic is about platform specific convenience code that is built in so you don't have to use native code.
When you say the Unity C# API must be platform agnostic, you are implying that classes such as https://docs.unity3d.com/ScriptReference/AndroidJavaClass.html do not exist.
Let me clarify in case you didn't understand what I wrote. Unity's code must be platform agnostic when using the Mono libraries. obviously when building to a specific platform such as Android (using gradle) or IOS (using Xcode) you can be as platform specific as you want. But if you want to build using the Mono backend that option is just not available to you
Hello, I'm working on my game and have a slight issue:
I want to fill an UI Image vertically using the fillAmount. The "formula" I thought of is the following:
percentage = currentValue / maxValue
Now, for anyone, this would be sufficient, but I still have a problem. I want the percentage value to be 0 not when currentValue is equal to 0, but I want the percentage value to be 0 when currentValue is equal to 25. The maxValue is 43, so I need a function that tells me at what percentage of the range from 25 to 43 the currentValue is, but I couldn't find or think of anything yet.
Thanks in advance.
But basically just:
(currentValue - minValue) / (maxValue - minValue)```
Actually you can also just directly use https://docs.unity3d.com/ScriptReference/Mathf.InverseLerp.html
since your target range is 0-1
Of course! Thank you so much, I should've thought of that earlier 😅
I was trying to work on a ye olde launcher and decided to try making it look nice in unity and load it as a scene and then noticed the title bar/border and wondered why it exists in 2024
probably simpler to just make a launcher as a separate standalone application
yeah i was thinking about going back to the first application instead of trying it in unity... i was really hoping to get this effect:
definitely a separate application than the main game.
