#archived-code-general
1 messages · Page 404 of 1
Why is that necessary?
Ah, so it wasn't even a code issue
It seems to generate new random GUID, I don't see a reason why it wouldn't change
to serialize the field which you lose
fair enough
but is it supposed to visualize something? am i supposed to see the spherecast? if so, i dont see crap
Oh!
Yeah. Show the window
I think it's different from version to version
is this the spherecast?(its inside of the player) and it seems to react to change of the query color
Hard to say from my end lol
the anatomy of the player lmao
Idk which one is the spherecast here but both look incorrect
The bottom ball would already start inside the ground and therefore not detect it
The top (cyan) part looks like it never leaves the player
the cyan is the query and the yellow is a trigger to detect ground
So your spherecast is too short
Or is it hitting the trigger perhaps
It shouldn't hit triggers by default AFAIK
and too large for some reason
the yellow ball and the cyan ball has .4f radius
@winged tiger Sorry, I didn't read the whole code, I think reaz is right though. The way you have implemented it, it seems to me like you would have to save the scene every time SetDirty is called though to which there might be a better solution that doesn't require manual saving
oh, yeah
the trigger sphere is a child of the player object
forgot about that
anyway thanks for the help
i will use the physics debugger very often i think
Actually this isnt what I wanted exactly. When this object is saved as a prefab (logicly) the persistentID is saved as well. Is there a way to detect when an object is placed in a scene?
That is actually a problem if you then create multiple instances of the prefab. The first thing that comes to my mind would be to use ISerializationCallbackReceiver.OnBeforeSerialize and set the string to null if the GameObject this script belongs to is a prefab. (I have not used OnBeforeSerialize myself so this might be very wrong. Something like this could work though)
If you "placing" "object" in scene by script you actually know it. If you place it by drag and drop (drag prefab) it "detect" itself, just use Awake.
But Awake gets called during initalization (so eg. when entering playmode) so it isn't a good option
and since you added ExecuteInEditor atttribute it also execute Awake each domain reload
That might work
Yeah
initialization in this case is the same as detecting, so that was accurate anserw to your question
Not really. I asked for detecting when an object is placed on a scene.
then remove [ExecuteInEditor]
That would work but there is this problem
anybody who is skilled at coding that can help me?
Don't crosspost please
so you want to save GameObject with unique presistentID as prefab?
What if there are several GameObjects of the same prefab?
I don't want that
That's the problem, it should be persistent between scene objects but not for prefabs
When this object is saved as a prefab (logicly) the persistentID is saved as well
I stated the current behavior
You can write an editor script that assigns IDs to all objects in the scene that don't currently have one
You can also assign a new ID to objects that you instantiate at runtime -- you'll need to do so in a consistent way, of course.
I suppose that'd be the job of the object's owner.
I thought of that, and I will do that if nothing else will be good
I'm not aware of a way to react to a prefab instance appearing in the scene
PrefabUtility.IsPartOfPrefabAsset might prove useful.
Returns false if the object is part of a Prefab instance in a scene
I guess you could use [ExecuteAlways] and then check yourself in Awake
being careful to avoid doing anything if you're in a prefab stage
Yeah that's a little scary
going with that method :c
But doesn't that not solve the problem of dragging object from the scene into prefab serializing the ID as well and therefore making all instantiated objects have the same ID? To avoid that something like this could be done though to never serialize the ID to a prefab:
public void OnBeforeSerialize()
{
if (PrefabUtility.IsPartOfPrefabAsset(this))
{
persistendID = null;
}
}
well, yeah, but it's serialized as an override on the prefab instance
You'd need to write the code so that it never tries to modify an actual prefab asset
It must only ever touch prefab instances
This gets kind of scary :p
what code? the code on OnBeforeSerialize or the code that generates the IDs?
dragging object from the scene into prefab
Are you talking about prefab creation here?
Yes
But if this code was used, wouldn't the ID never end up on a prefab?
Thought the use for ISerializationCallbackReceiver is to prepare data to be serializable, in his case it is serializable, a serialziable id string exactly
other case he doesn't need to assign persistent id in Awake for a prefab, so it stays empty
I haven't done either so it might or might not work but I think OnBeforeSerialize is called every time the prefab is created (having this script) or the component modified on the prefab so it should always override null for every instance lying on a prefab if I'm not mistaken
also when he assign persistent id in Awake for GameObject it should dirty and save the scene, to serialize it in to scene asset
That's what it's often used for but I don't think it is limited to data that cannot be serialized. Instead I believe any data to be serialized can be modified before the serialization
it can but it doesnt make sense, i mean for this case, since data is all ready to be serialized
and there is also internal serialization, so everytime this gameobject will be viewed in inspector the callback will be trigged
Data sure is ready to be serialized but persistentID shouldn't be serialized, that's the problem if existing object is made into a prefab
changes done to a prefab, after instantiating in scene, are stored in the scene
basicly every game object is serialized as a part of a scene asset, if it have prefab it is saved as prefab blueprint + changes
thats what modified gameObject from a prefab generates
I know, I'm talking about an edge case which is the same thing but opposite. If you have object in the scene that is not a prefab yet and drag it into the project folder to make it into a prefab, the serialized persistendID will get serialized in the prefab
if check if its prefab, which you proposed, would solve this issue
But where would you do that if not in OnBeforeSerialize?
Now that I think about it, I'm not too sure myself that the solution that I provided would work anyways though. It is very well possible that this is not recogniced as a prefab by PrefabUtility.IsPartOfPrefabAsset at the time the prefab is first time created. Should try that though to make sure
Not sure for now, could use AssetsDatabase, but i would avoid ISerializationCallbackReceiver for this case
the best would be if the user would just take care of it himself, since its one time thing to do
@winged tiger Now that I tried it, ISerializationCallbackReceiver does seem to work as I thought. It seems to be quite excessive though, I thought unity would do the serialization only when something is changed but it seems to be called all the time prefab or object with the script is selected (with inspector open). I don't have any experience with AssetDatabase but with it there might be a better way than with the serialization callback. Making the user be aware of this edge case might be good enough too. The name of NetworkObject suggests that this script would be used quite much so it wouldn't be a surprise if this edge case happened though.
with AssetsDatabase you can make Scripted Importer and check the prefab/ modify it before it get imported
Hey guys, I'm trying to add xml documentation to my project which I then use docfx to build a static site for. I'm using a CsprojPostProcessor to add "<DocumentationFile>./Docs/File.xml</DocumentationFile>\n" to my Assembly-CSharp.csproj. However I don't know how to trigger this csproj to generate the xml. I've tried reloading the domain and deleting library folder. So far I've only gotten it to generate the xml using an msbuild command, does anyone have any pointers?
Nevermind I figured it out, docfx automatically builds the csproj given the correct path.
Sorry, I've asked this before, but I forgot. What is the class/variable called that allows you to select a function.
I think you are thinking of delegates?
Or maybe you're thinking of UnityEvent
UnityEvent sounds right.
I am moving a rigid body with wasd input like this
private void FixedUpdate()
{
_movementVector = _input.x * transform.right * settings.moveSpeed + _input.y * transform.forward * settings.moveSpeed;
_rig.linearVelocity = new Vector3(_movementVector.x, _rig.linearVelocity.y, _movementVector.z);
}
How would I make it rotate on the y axis to face the direction the rigidbody is being moved? currently it moves to the right but faces forward
i tried this doesn't work correctly the rotation bugs out and spins infinitely as soon as i move to the right or left
if (_rig.linearVelocity.x != 0)
{
float rotationAngle = Mathf.Atan2(_rig.linearVelocity.x, 0) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0, rotationAngle, 0);
}
linearVelocity is world-space. transform the movement to localspace first
oh wait you're already doing that whoops
what is the issue right now?
im confused
they just want to rotate the rigidbody to face the direction they are moving in . . .
chat gpt figured it out. I was trying to make player movement work how it does in the original san andreas game.
if (_rig.linearVelocity.magnitude > 0.1f)
{
// Create a new vector that only has the X and Z components of the velocity
Vector3 direction = new Vector3(_rig.linearVelocity.x, 0, _rig.linearVelocity.z);
// Check if the direction is not zero
if (direction != Vector3.zero)
{
// Calculate the target rotation based on the direction
Quaternion targetRotation = Quaternion.LookRotation(direction);
// Smoothly rotate towards the target rotation while maintaining the current X and Z rotation
Vector3 currentRotation = mesh.rotation.eulerAngles;
var rot = Quaternion.Euler(new Vector3(0, targetRotation.eulerAngles.y, 0));
mesh.rotation = Quaternion.Slerp(mesh.rotation, rot, Time.deltaTime * 5f);
}
}
there may be a better way to do it but it acheives what I need until I feel like fucking with it again
i would use LookRotation with your _movementVector to get the rotation, then use a physics rotation method to turn (rotate) . . .
you might want to use the input vectors instead of the velocity
The problem with that is if the player moves to the right and starts facing right and then you stop and move to the right again you will turn another 90 degrees and face the camera
velocity should be fine. wait, what is mesh?
its the visual object its a child object of the rigidbody
if I dont apply the rotation to the visual representation of the mesh
then the rb spins indefinitely and walks in a circle when holding down d
may I ask why you would use phycis to rotate?
oh i see what the intended control is now lol
idk if you ever played it but im tryhing to copy the movement they have for cj in the orignal san andreas game
imo its the only third person game that made sideways movement not feel ass
i haven't no, so i was trying to imagine what that was
if you''re facing the direction the camera is looking and move to right your character will look to the right and keep walking in that direction
unless you're aiming then you strafe
because you're using physics for movement . . .
but im not actually rotating the rigidbody im rotating a child of it
and if I do rotate the rigidbody it will continue to walk in a circle
you'd need to use the camera forward/right instead (projected onto the xz plane and normalized, probably) with that route
you mean it continues to rotate even after releasing the input?
i dont want it to continue to rotate, I just want it to face the direction of the movement and keep looking that way.
oh wait waht
discord can't embed mkv
mp4?
use streamable or an mp4 . . .
that's def not right . . .
it keeps rotating the entire time I hold d
this is the desired behavior
but i can only achieve it if I rotate the child of the rigidbody not the actual rigidbody itself
if (_rig.linearVelocity.magnitude > 0.1f)
{
// Create a new vector that only has the X and Z components of the velocity
Vector3 direction = new Vector3(_rig.linearVelocity.x, 0, _rig.linearVelocity.z);
// Check if the direction is not zero
if (direction != Vector3.zero)
{
// Calculate the target rotation based on the direction
Quaternion targetRotation = Quaternion.LookRotation(direction);
// Smoothly rotate towards the target rotation while maintaining the current X and Z rotation
Vector3 currentRotation = mesh.rotation.eulerAngles;
var rot = Quaternion.Euler(new Vector3(0, targetRotation.eulerAngles.y, 0));
mesh.rotation = Quaternion.Slerp(mesh.rotation, rot, Time.deltaTime * settings.timeToTurn);
}
}
it keeps rotating because it keeps going "right" of the transform, which is also being rotated
see above^
then smth is wrong with the code . . .
yeah exactly
I tried this earlier and couldn't get that right either but let me play with it some more thank you for the advice
this was the answer its now working
Having rigidbody issues, as mentioned in #⚛️┃physics .
just make the game the executable, and driven by scripts inside it.
dont crosspost. all youre missing is a physic material
I would like to create a 2D game development tool like RPG Maker. Is this possible with one-person development?
Can I extract a game created with development tools made with Unity into an executable file?
Made a new physics material. Still clings.
Setting it to "Frictionless" gets rid of the cling, but it makes my movements a bit slippery.
Most of the data is in text files and nothing technically prevents you from doing anything you would normally do in C#.
So can you make it?
put the frictionless material on the wall instead
make the wall not have friction instead of the player
or add linear drag to the player, to compensate for the missing friction
You can, yes
I want to create a mobile game development tool.
So, is it possible to create a game using the game development tool made by Unity and extract it into another apk file?
unity is a intended as a game engine, but doesn't mean you have to use it like that (eg, simulations, 3d environments, etc)
If it's possible with C#, it's possible in the Unity editor.
I really want to create a mobile game development tool!
If I create a game creation tool, can I use it as a game portfolio?
for a game portfolio? i don't think much of making a gamedev tool overlaps with gamedev itself, save for ux/ui i guess (though still a different kind of ui)
it'd be more like, unity/c# familiarity, and making an app via unity rather than making a game
Ah, would it be better to use Unity as a game creation tool like this? Would it be better to make it with something like Android Studio?
"better" is very dependant on your personal experience
if you're like, really proficient with c# and unity and not at all familiar with java/kotlin and xml, then it could be a better option
that's an extreme case
it'll be possible with both
Do you recommend making it only with the Aha language library?
no clue what that is
i can't recommend anything in this space, i don't have any experience here
Is there a way to extract the executable file from a game creation tool made with Unity?
what platform?
if its running on desktop the unity game could launch .bats to compile exes etc
Mibile
see scorpion engine for a great example
the tool could export mobile games easily but not if it wasnt running on a desktop OS etc.
Why are you so dead set on that idea? If you're gonna make a game creation tool, you're gonna need to have enough expertise in programming to not rely on unity.
It is scheduled to run in a mobile environment.
The tool or the games that it would create?
This is something I've wanted to do for two years.
I think the tool
i doubt u could make an APK etc on mobile it self, maybe could build on cloud and return one though
So basically a game creation tool running on mobile and building mobile games?
Yes!!
would it not be easier, to have the game itself output levels, that users can then load into the game?
I'm not good at Unity either, but I'll try making it for practice!
this is not a practice project
you have quite a large scope currently
this practice is gonna be like, 3 years
Then this is not gonna be straightforward due to what Gaz said. Also, mobile apps don't have exe files. And then again, if you're gonna do that you're gonna need to have several years of experience as a programmer. At which point you'll probably realize that there's an easier way to implement what you want.
id just build a game with a level editor inside, and have easy way to make and launch levels, most of my games have that
Yes I know. I want to break through my limits!
current game i can make levels in it on say my steamdeck, and test them all on the move without a pc
or my switch etc
cant afford steamdeck yet but thats the plan lol..
Wow
This is not breaking through limits. It's like trying to build a nuclear reactor without knowing school physics even.
haha
Ah... I see.
Start simpler. Increase the difficulty steadily. Focus on few areas of expertise. Eventually you'll get to a level where you'd be able to plan and execute what you want without asking for an advice here. That's when you know you're ready for it.
So, shall we create another project and practice?
Let me show you the games I've made so far!
It's currently at this level.
quite basic still but good start
making tools can be horribly overwhelming at times
and not that fun
almost lost interest in my whole game making this tool.. but got there
Maybe start from making similar games in unity. Maybe higher quality and with additional features.
From the convo so far it seems like you're new to unity.
Ah, then I will improve my skills and make it.
I’ve been doing it for about 2 years now!
yeh build a basic engine, then build a basic editor for the engine
What kind of game would it be best to get a job making?
so eventually u will have a way to make "levels" for the game engine
Yes
then just load them levels up in the game engine, and youre half way there
one that you like
and preferably not those weird mobile games
Yes
2 yrs, i spent like 30+ yrs now and im still stuck everyday 🙂
coded every single day since mid 90s
What about horror games? 2D
I want to make a horror game or RPG! Which will your company prefer?
doesnt matter what u make so long as u have fun, learn and finish it, though there are some genres that do better, (this guy talks about that https://www.youtube.com/watch?v=uPOSZ_jhCaw )
🎮 Get Chris' Masterclasses! Ending SOON! https://cmonkey.co/howtomarketagame
✅ Get my C# Complete Course! https://cmonkey.co/csharpcourse
🌍 Game Dev Report Newsletter - https://cmonkey.co/gamedevreportnewsletter
🎮 Play my Steam game! https://cmonkey.co/dinkyguardians
❤️ Watch my FREE Complete Courses https://www.youtube.com/watch?v=oZCbmB6opxY...
Let’s take a look next time!!
platform games tend to not sell well apparently, shame because one of my main games is one lol.
nice, went to korea, cool place, im living in taiwan 🙂
Thank you
I want to make a horror game, but I'm worried that it will be difficult to create a horror feeling.
I'm afraid of something
Can I do it?
yeh its difficult, just consult existing games
silent hill, PT etc, resident evil etc.
Then wouldn’t it be better to create a genre other than horror?
P.T. Silent Hills Gameplay Walkthrough PS4 PRO PS5 PC No Commentary 4320p 60fps HD let's play playthrough review guide
Showcasing all cutscenes movie edition, all boss fights / boss fights, side missions, upgrades, outfits / costumes, all characters, best moments, final boss and true ending, secret ending.
PC Version by Artur Łączkowski (PT Em...
Oh
create what you personally want to play
Hello, is there anyway to insure that something within my start function will only be called after unity checks for collision enters, ie when the object spawns check for collisions before running start (beyond just adding a delay)
I want to make and play my own horror game!
OnCollisionEnter()?
those are on different loops
what are you even trying to do?
then do it @earnest gate
sounds like youve got an https://xyproblem.info there
yeah onTriggerEnter2D
All right!
that's gonna be called after Start, if anything
which is the problem, is there a way to prevent this?
for more context, I am working on room generation and checking if a room has already generated in a spot
I'm curious!
This isn't a coding question. Use #archived-game-design.
Yes
check in start/awake and if it is, then just destory the object?
or you might want to just have some centralized system that can keep track of it itself
how can i check within the start function? I have only been taught collision detecting using the collision functions
raycast/overlap & friends
but this would probably be better
that is probably true, ill work on that. thanks for the help
Current problems with my Rigidbody Character Controller
1. Rigidbody Forces can be easily counteracted by player input.
2. Bumping into walls doesn't seem to slow your movement.
3. No slope limit. Anything less than 90 degrees can be climbed.
4. The slightest dip in ground level will end up with the player airborne.```
Current problems with my Rigidbody Character Controller
you aren't supposed to have both on a single gameobject
made it work by storing a representation of the rooms pos into a list, then on the start of each new room checking if its pos is already within the list (if it is, destroying it)
Problem #1
does pressing left/right also stop the movement?
yep
it is your movement system most likely, im guessing you are setting the velocity based on the input rather than adding it to the current velocity?
Problem #4.
I'd have to look at the code again. @arctic sparrow is the one who developed it.
im not familiar enough with the physics engine for the other problems sadly, but when you get a chance ping me and send the code for that
It uses AddForce.
It's derived from Dave/GameDev's third person controller.
Problem #2
so which are you using?
Rigidbody
Problem #3
It's almost 5AM. I should go.
yeah im about to head to bed too, ill take a look tomorrow if no one else helps you tonight
- use forces or add to the velocity instead of setting the velocity directly, and maybe check for being airborne to give less control
- not seeing the issue there, do you want to have friction with the wall?
- make a check for the normal of the ground, maybe
- snap to ground or something of the sort, there's probably resources online for this
actually for 1 you might want to just lock controls for the duration of the launch? that seems like a specific instance rather than a general issue
That won't work for my purposes. There are some games out there like Quake where, after going off a jump pad, you're able to adjust your trajectory mid-flight.
ok so your air strafing is just too much then
For 2, I'd like to have friction with the wall, but only laterally. Having it vertically results in being able to cling to a wall.
I don't understand though how moving to the side mid-flight somehow cancels out all the speed applied to the character...
i think you'd have to check for collision and apply that manually then
for 1:
you have an acceleration value, but you're doing addforce with velocity change mode
so that's, just, a lot, and seems like your max speed is governed by max speed or linear drag settings
you might want to reduce that
My bro says that our code should be able to differentiate speed applied via a player's input from speed applied by the environment...
they'd just be added together anyways
i don't think there's really a point to doing that
it's a physics thing, it works on colliders
when in doubt, consult docs
Casts a ray, [...], against all colliders in the Scene.
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics.Raycast.html
Physics.Raycast operates on Colliders. There are other raycasts available for other things.
can someone explain what an event subscription (+=) is
you subscribe to an event
later, that event can be triggered, and the delegates that have been subscribed will each be called
what do you mean by subscribe? to recieve updates or something?
You can think of an event as a list of methods to be called when that event is triggered.
Subscribing is adding a method to that list
one event can have many subscribers. you simply subscribe to the event and wait until it is being triggered somewhere.
playerControls.PlayerMovement.Movement.performed += i => MovementInput = i.ReadValue<Vector2>();
in this code what does the += do, i am using it in an onEnable method so does it add it to that method?
i => MovementInput = i.ReadValue<Vector2>() is a lambda
it's essentially a function but as a value
when performed is invoked, that function will be run, along with anything else subscribed
so it basically means when when this action is performed you will do this
yes
can i replace lambda by another variable or does it have to be i
you can.. replace the entire lambda with a method reference?
do you mean the lambda parameter?
the i there is just a name, like a method parameter
you can name it anything
the lambda in full would be (InputValue i) => { MovementInput = i.ReadValue<Vector2>(); } but it can be shortened a lot
single parameter, so the parens aren't necessary
type of the parameter can be inferred
single statement, so the braces aren't necessary
does scriptableobject being recognized automaticly by unity during the runtime becuase i am deleting one and making second as player and it could not be recognized
to use navmeshagent is better way i think
and with bake you can move in the right way
You should make it easier for yourself and use a dedicated method rather than a lambda
playerControls.PlayerMovement.Movement.performed += UpdateMovementInput;
...
private void UpdateMovementInput(MyValue i)
{
MovementInput = i.ReadValue<Vector2>();
}
This is the same, but now it's by method reference and you can also unhook from performed with performed -= UpdateMovementInput should you ever need to stop calling it
And just to summarize, performed is an event and += basically means "I want to invoke the right part when the event is called"
yes -- it's impossible to unsubscribe an anonymous function if you don't keep a reference to it
+= is a short way to do addition, like i += 5 adds 5 to a variable
foo += () => { };
foo -= () => { };
these two anonymous functions have nothing to do with each other
Exactly
I was tickled when I found out about delegate addition
I'm sure there is some complex shenanigans that does end up allowing it, but now natively build in
var what = (System.Action) Update + Update;
Anyway just 2 cents because performed += i => MovementInput = i.ReadValue<Vector2>(); is very hard to understand in general
this also feels worse than just reading the value constantly
I prefer to only react to phase changes for button-like inputs
so im not just stupid
i was going through this tutorial and spent 30 minutes trying to figuire it out in chat gpt
It's also just written poorly
playerControls.PlayerMovement.Movement.performed += (i) =>
{
MovementInput = i.ReadValue<Vector2>();
}
I'd write it like this
That is if you don't want/need a method
i see
So maybe that is more clear
in this code in the handle rotation method instead of giving targetDirection same the values as MoveDirection cant i just directly put Quaternion targetRotation = Quaternion.LookRotation(MoveDirection)
its written at the end of the handle rotation method
Sure why not?
this is not the place for self advertising
Hey all, I'm trying to make a movement system where i can pitch and yaw in space. Here's my code:
private void Rotate(Vector2 axisValue) // axisValue.x = yaw (y rot), axisValue.y = pitch (x rot) (This hurts my brain)
{
if(axisValue != Vector2.zero)
{
Vector3 axisRotDir = new(axisValue.y, axisValue.x, 0);
axisRotDir.Normalize();
Vector3 torqueDir = transform.rotation * axisRotDir; // Direction of the torque relative to world rather than local object
RotateInDirection(torqueDir);
} else HaltRotation();
}
private void RotateInDirection(Vector3 direction) // Applys torque in a direction and damps change in velocity
{
if(rb.angularVelocity.magnitude < MaxRotationalSpeed)
{
float rotationalThrust = RotationalThrust; // Preventing repeat multiplication calculations
direction.Normalize();
isTryingToRotate = true;
// Difference between the desired direction and current direction
Vector3 dirDifference = direction - rb.angularVelocity.normalized;
dirDifference.Normalize();
// Damp in the opposite direction to the difference
rb.AddTorque(dirDifference * (MaxRotationalThrust - rotationalThrust + overheadDampingThrust));
// Apply a continuous torque in the desired direction
// If current speed is less than 10% of maximum speed, give some extra thrust to make rotation feel more fluid
rb.AddTorque(direction * (rb.angularVelocity.magnitude < (MaxRotationalSpeed / 10) ? rotationalThrust * 2 : rotationalThrust), ForceMode.Force);
}
}
private void HaltRotation() // Same as brake function, but for rotation
{
if (rb.angularVelocity != Vector3.zero) rb.AddTorque(rb.angularVelocity.normalized * -(RotationalThrust + overheadDampingThrust));
}```
I've gotten a similar system working for movement, but quaternions mess with my brain so much and implementing rotation like this causes all sorts of weird effects. Im using a controller joystick in order to control this rotation (that's passed into the rotate function). Does anyone know what i may be doing wrong?
No drag is affecting this rotation and there is no gravity, only the damping i've added to get rid of rotation in the directions im not currently trying to rotate in
(If you want me to move this to #archived-code-advanced i'll be happy too, but i wasn't sure whether or not it would qualify for that)
it's not advanced
The part where you're subtracting angular velocity from a direction vector is completely nonsensical
I would say that part definitely needs rewriting
i Did that same thing for damping my movement, so i just copied it over to rotation and hoped it would work if im being honest lol, even without it though, it still doesn't work, as i anticipated that the damping probably wouldn't work out the same
If it's working in the other place it's from sheer dumb luck or that part is just getting overwritten
It's like "Walrus - potato"
How would i go about doing damping properly then? I can't just add drag to the rigidbody in the editor as i don't want drag in the direction im moving if that makes sense, but if im travelling for example forward and then decide to go right, ill still have a bit of that forwards velocity. Hence why i thought finding the difference between direction im trying to go and the direction im currently going, and applying an opposite force to that would work, which it seems to do for movement
But "direction I'm currently going" is not what angular velocity is
Your thought process is sound, the code just doesn't reflect that
private void ThrustInDirection(Vector3 direction) // Applies a force in a direction and damps change in velocity
{
if (rb.linearVelocity.magnitude < maxSpeed)
{
direction.Normalize();
isTryingToMove = true;
// Difference between the desired direction and current direction
Vector3 dirDifference = direction - rb.linearVelocity.normalized;
dirDifference.Normalize();
// Damp in the opposite direction to the difference
rb.AddForce(dirDifference * (maxThrust - thrust + overheadDampingThrust));
// Apply a continuous force in the desired direction
// If current speed is less than 10% of maximum speed, give some extra thrust to make movement feel more fluid
rb.AddForce(direction * (rb.linearVelocity.magnitude < (maxSpeed / 10) ? thrust * 2 : thrust), ForceMode.Force);
}
}```
So this logic for damping for movement is fine right? I just cant directly apply this to angular velocity as well?
I think the confusion is coming from the naming of your "direction" variable maybe?
Where is that coming from?
I'm assuming, as its name implies, it's a direction vector, which wouldn't make sense here
private void PlanarMove(Vector2 axisValue)
{
if (axisValue != Vector2.zero) // If player is trying to move, apply a proportional force in that direction
{
Vector3 camForwardDir = Camera.main.transform.forward;
Vector3 camRightDir = Camera.main.transform.right;
// Flatten vectors to be planar in X/Z
camForwardDir.y = 0;
camRightDir.y = 0;
// Re-normalise vectors with new planar value
camForwardDir.Normalize();
camRightDir.Normalize();
// Resolved movement direction from input
Vector3 moveDir = (camRightDir * axisValue.x) + (camForwardDir * axisValue.y);
ThrustInDirection(moveDir);
} else Brake();
}```
That is coming from this, its just the direction that i want to go
You mean moveDir?
yeah
this is just movement im talking about rn though
i was just trying to take that same logic and apply it to rotation. The code i just showed was purely for my movement, which as far as i can tell works as expected, i was just showing you what i was referencing when making the rotation
Sorry i realise i've explained this badly
If you're talking about getting it to Face a certain direction that would be analogous to code that gets your object in a certain position, not to a certain velocity
Here's my whole code for reference: https://pastebin.com/5nsWsYSR
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.
Desired position -> desired rotation
Desired linear velocity -> desired angular velocity.
What I believe you are trying to do is take code that gets you to a desired velocity and trying to use that to get to a desired rotation
yes, that's what im trying to do
The correct analogous code would be code that gets you to a desired position, which I don't think you have
So you'll have to write this from scratch
Basically it's a second order integration on top of "desired velocity" code
Right, i see what you mean. I just really struggle to wrap my head around rotation comparent to movement
Think about what code would look like to get to a desired position
You'd first have to accelerate towards the position, then you'd need to decelerate as you arrive there
It's the same for rotation
well i'd need to work out the difference between my desired position, and my current. And then apply a force in that direction in order to get there
yeah
the thing is for rotation i dont have a desired rotation i want to be at, i just want to rotate in a direction based on my inputs
But that's exactly the same
The desired rotation is just basically Quaternion.LookRotation(input direction)
(adjusted for the camera etc)
i want it to be physics based though, wouldn't that not be physics based?
This is just math
This gets us the directions and rotations we will use physics to achieve
I didn't say to just immediately set your rotation to that
It's our target
Is there a way to create an editable bounding box for a script (sorta like what you can do with a box collider)? Creating a public Bounds technically works, but I want the ability to see and edit it in the scene view.
right
You would use that in a custom editor's OnSceneGUI or such
Where im not really following you here is how im figuring out my "target", because im just rotating in a direction until i decide i don't want to rotate anymore. Sorry if i'm slow at picking this up
Thank you, I'll do some looking into this.
The target is whatever direction you should be facing based on the input
The current is whatever direction you're currently facing
If you mean that there's not a "face left if I'm holding left" and instead there's a "apply clockwise torque when I press Q", well that's much simpler
float density;
for(int i = 0; i < NumSteps; i++){
RayOrigin += (RayDirection*StepSize);
//Get the density of the sphere.
float SphereDistance = distance(RayOrigin, Sphere.xyz);
if (SphereDistance < Sphere.w)
{
density += 0.1*DensityScale;
}else { }
}
return exp(-density);
Thats a script inside of my raymarching thingy for clouds
For some reason, I get these errors
im very sure these errors are caused by the "return" portion
because if I comment out the return. these errors vanish, and others take its place, that the output isnt working
the 'some reason' is very explicitly spelled out in the error message
Yea
But i dont really understand why its doing this
(im stupid)
In C# you need to specify the function's return type.
If you wrote "void" that means "this function doesn't return anything"
I think that's HLSL
Well fine, same thing though
Is it a custom function node in shader graph?
the only type i see is "string" or "file"
So it doesn't even have a body that you wrote void in?
You need to use an out parameter for that iirc
In any case #archived-shaders
Assign that then instead of writing return
im pretty sure it works properly for the out
kk
wait
that actually worked
Thanks man
Ofc
did you expect it to not work
Im kinda stupid
aren't we all
And tried MANY things that didnt work
yeah, that's what i'm aiming for, except pitch and yaw are on an analog stick axis, and roll is on 2 buttons
So I have been messing around with cinemachine and character movement and I got it down, and works as should. I understand what is happening but I dont understand why. In the code below I get the direction that character should move according to the cameras position but for example I would think forward direection = cameras transform. Forward but what worked was .right and for side movement I found that .forward works to move the player left and right according to camera position. Is this because the camera and the player object have different directions, if that makes sense. here is my code:
{
if (verticalInput > 0)
{
// Get the camera's forward direction
Vector3 forWardDirection = -cameraTransform.right;
transform.Translate(forWardDirection * forwardSpeed * verticalInput * Time.deltaTime);
}
}
void MoveSide()
{
if (horizontalInput != 0)
{
// Get the camera's side direction
Vector3 sideDirection = cameraTransform.forward;
transform.Translate(sideDirection * sideSpeed * horizontalInput * Time.deltaTime);
}
}```
Never mind I think I found my issue, in scene view my players (sphere) x position is different from cameras x position
im sure someone had this issue before
how to stop the player from sliding down the slope when jumping?
What do you mean, how can you slide on a slope while you are jumping?
Show a video of the issue?
i have shortened it a lot lol
when you jump and land on a slope, the player slides down
its like from the beginning of the project and i want to finally fix the issue
I don't know anything about your game, are you moving with a Rigidbody/Rigidbody3D? CharacterController? What does the movement code look like?
You could just manually set your velocity to zero when you are on the ground and not trying to walk
rigidbody3D, setting the velocity to 0 wont work for my type of game(fast paced)
should i send the slope code?
setting the velocity to 0 wont work for my type of game(fast paced)
What do you want to happen when you land on a slope?
continue to move the player?
now i just realized im fuken dumb
those two things almost cant coexist
setting the rb to velocity to 0 (when on a slope) should fix your issue then
idk, i have brain damage from unity lmao
so, it doesnt work but there is a second issue i have encountered
the spherecast lags behind the player or the physics debugger is not showing the true position
still learning my way around the new input system. is there a delay on registering actions on Start() via InputWhatever.action.Started compared to just getting a value in Update() via InputWhatever.action.ReadValue<>?
ReadValue seems to be working flawlessly for my character's 3D platformer movement, but I'm not sure if I should be using that or Started/Performed for jumping
oops, comlpetely misread that lol
Start runs before the first Update call.
Note that if the control was already being held down when Start ran, I'd expect for the performed callback to not get invoked at all
(until you let go and then press the control again)
I'm most likely not going to be distinguishing between tapping and holding jump for now, so I guess started will work best
started and performed will be invoked at the same time if you don't have any interactions on your action
so I could just
void Start()
{
(...)
I_jump.action.performed += _ => Jump();
}
void Jump()
{
// Do stuff
}
without worrying about delays then, right? neato
I'm not sure what the "delay" would be here
I thought you might've been talking about a delay before you can start receiving actions t all
unity taking a while to detect an input. I'm just assuming the worst
I would not expect there to be any appreciable difference, beyond exactly where in the frame the performed event is invoked
I don't know exactly where it happens
you can set a breakpoint at Jump and see for yourself where in the player loop the input system actions are resolved. there is a lot of documentation about this too. what's yoru goal?
just wanted a quick answer without needing to do performance analysis myself, just being lazy
this worked fine
Hey all, I'm trying to rotate my character in space, in 3 dimensions, and here are the functions i've written for it:
private void RotateInDirection(Vector3 direction) // Applys torque in a direction and damps change in velocity
{
if (direction.magnitude > 1f) direction.Normalize(); // If will gain extra accel from diagonal, normalise
float thrustModifier = rb.angularVelocity.magnitude < (MaxRotationalSpeed / 10) ? RotationalThrust * 2 : RotationalThrust;
rb.AddRelativeTorque(direction * thrustModifier, ForceMode.Force);
}
private void HaltRotation()
{
if(rb.angularVelocity.magnitude <= 0.1f) rb.angularVelocity = Vector3.zero;
rb.AddTorque(rb.angularVelocity.normalized * -(RotationalThrust + OverheadRotationalDampingThrust), ForceMode.Force);
}```
I have no drag on the rigidbody, and have not yet implemented my own damping system, as am just trying to get the basics down first. This mostly seems to work (i have only tested with pitch and yaw currently), but for some reason yawing seems to happen much quicker than pitching, but i cant figure out why, does anyone know what im doing wrong?
Does your character have a non-spherical collider?
I believe the rigidbody tries to model the moment of inertia properly
its a capsule collider, yes
A capsule is much easier to spin around its long axis than any its short axis
Perhaps you want to ues ForceMode.Acceleration to get a fixed change in angular velocity, no matter how much inertia there is
is there a quick way to disable it, or do i just have to multiply it by the difference in lengths
Just to double check, your direction.magnitude IS bigger than 1f, yes?
If you don't want to factor in inertia, don't use ForceMode.Force
direction is passed using values obtained from the position of a joystick. So it can be less than 1 i only push in one direction or if i dont push the stick out all the way yes. I realise now that code may be redundant, im not sure why i did it really
This function is getting called every FixedUpdate() though, wouldn't doing forcemode.acceleration cause it to increase in acceleration every update?
or is that not how it works
No.
There is no "memory"
It just accelerates the rigidbody without considering its mass
I don't think it's redundant in that case. It provides control if the player wants to rotate slower, but disallows the trick of rotating faster by rotating in multiple directions at once
calling AddForce with ForceMode.Force does not cause the force to build up over time, either (:
Yeah that was what i was intending to avoid, so i think thats fine then
Yeah sorry, not sure what i was thinking there, thanks. Im a bit slow when it comes to physics/maths problems like this, always takes me a while to wrap my head around
i wonder if you got that prediction script, from past days, working right
I realised that my technique was entirely flawed due to an edge case (literally). I was casting a ray to detect things infront but what i would've needed to do instead would be to project my entire body forwards, and then check if that overlapped with anything, as the ray coming from the centre could miss a corner, when in reality the collider would still hit it, I will probably go back and implement it, but i decided to see how sickening damping it would actually be first, because it might not be that bad
Could someone help me understand why a list is returning null immediately after its class is instantiated?
It's a non-Monobehaviour C# class. I instantiate it like this:
myClass = new MyClass();
..but the very next line, a Debug.Log indicates its contained list returns null.
The list is declared like this.
public class MyClass { public List<OtherClass> myList = new List<OtherClass>(); }
are you sure the list is null? can you show the code where the NRE actually happens?
OK it was because my init code had serialized the class and on restart had deserialized it, thus no lists. Duh
The following code works to rotate an object but it has a problem. The higher the degree of rotation the faster its rotating. Its happening because the it has to interpolate a larger span in the same amount of time but I am not sure how to fix that
Quaternion.Slerp(from, to, Time.deltaTime * rotationSpeed);
using deltatime in an interpolator's alpha parameter is inherently "wrong". a lerp function's third parameter represents a percentage between the first 2 values. it then returns a blended value between "from" and "to".
this looks like a bandaid solution, but then again I dont really know what you're doing.
you can use Quaternion.RotateTowards() to get a constant rotate speed towards a target
it's true that using deltaTime as the interpolation parameter is technically 'wrong' because it can be greater than 1, but for any practical application it works fine as long as all you want is a smooth stateless interpolation towards a target
i use this technique to lerp (damp, technically) framerate-independently towards a value (not constant speed) https://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
No. Using Time.deltaTime is not inherently wrong. The formula is simply not correct.
https://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
double linked
The issue with using lerp that way is that theoretically, you'll never get to the target value
Also the interpolation curve is not straightforward to understand.
And there are better ways to damp the value than using lerp incorrectly
Yeah. Pretty much this. The interpolation curve no longer becomes spherical or linear despite the name of the function when people start plugging in delta time. It starts to get confusing as hell especially for newbies.
Hey guys ive been using the new input system with a blend tree for movement im on the last steps to being finished. As you can see the characters goes back to nuetral idle pose when movement stops. I tried to capture last direction but with new input system I kinda got lost. Im fairly new to this.
Is there any way to reopen a bug report that it says fixed?
How to reproduce: 1. Open the attached project "TestDrawMeshInstance-2021.zip" 2. Open the "SampleScene" Scene 3. Enter the Play mod...
This still happens in 2022.3
Well, kind of now that i read it better. This bug report is for play mode, in editor mode it still flickers
I am getting this warning in unity once I switch scenes in runtime in unity:
The referenced script (Unknown) on this Behaviour is missing!
I believe this is because this script:
using TMPro;
using UnityEngine;
public class VolumeStatusUpdate : MonoBehaviour
{
public TMP_Text VolumeStatus;
// Start is called before the first frame update
void Start()
{
GetComponent<UnityEngine.UI.Slider>().value = MainManager.Instance.volume * 100;
VolumeStatus.text = "volume: " + (MainManager.Instance.volume* 100) + "%";
}
public void NewVolume()
{
MainManager.Instance.volume = (int)(GetComponent<UnityEngine.UI.Slider>().value * 0.01);
VolumeStatus.text = "volume: " + (MainManager.Instance.volume * 100) + "%";
}
}
may be trying to access MainManager.Instance.volume before it loads. The MainManager script is in an empty object:
using UnityEngine;
public class MainManager : MonoBehaviour
{
public static MainManager Instance;
public int volume = 1;
public float mouseSensitivity = 10f;
private void Awake()
{
if (Instance != null)
{
Destroy(gameObject);
return;
}
Instance = this;
DontDestroyOnLoad(gameObject);
}
}
How could this be fixed?
Solution: #archived-code-general message
you aren't getting the issue when you load the scene directly and play from that scene?
I only created the empty object in the menu scene as that's the starting scene
iirc that error is when you put a component on a gameobject and then delete the corresponding script
the error should highlight what object has the issue
I may have forgot to drag the new script but it works as intended without it on the only place I think that may have happenned. I'll try
Tried to re-drag it, didn't fix it.
that's not what im saying the issue is
I only have that first script there
It would be better to ask in #🔀┃art-asset-workflow
thanks so much
Can any one help me fix my errors
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 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.
not when you don't give us any info: !ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
Can we dm?
I'm using the unity pool namespace for my pooling of enemies. However, when I am prewarming I do
{
for (int i = 0; i < initialPoolSize; i++)
{
Health health = healthPool.Get();
Debug.Log($"Prewarmed Health instance: {health.name}");
healthPool.Release(health);
}
Debug.Log($"Total objects in pool after prewarm: {healthPool.CountInactive}");
}```
However, the Release function actually removes it from the hierarchy instead of just inactivating. From what I understand this isn't expected behaviour. Any ideas? (if I comment out the Release() function they are definitely being created)
no, this server exists for a reason
just for your info, you can take screenshots via win+shift+s
Unfortunately not, I am currently getting help myself 
🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.
📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!
💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.
For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting
so first off, use screenshots.
Ok
secondly, why do you have an assembly inside Scripts?
What’s an assembly?
the Assembly-CSharp, do you literally have that folder?
Yes
where did you get that
Idk
did you download some extra library or something
what have you done so far
what are you trying to do
Scripting
you really aren't giving much info to work with
30 errors
that's not what im asking, no
Ok
what are you trying to do
The scripting for playfab authenticator
where did you get this gorrila networking thing
did you download them somewhere, did you install an asset, did you write them yourself
I downloaded it somewhere
alright, where did you download it from
A discord server
A zip
...and there was an Assembly-CSharp folder in there?
By the way, where did you see the assembly seas sharp?
Auto correction sorry
C sharp
in the error message
Ok
what does the file in question even look like to have all those errors
Why did it get rid of all the errors?
why did what
@buoyant kayak Do you have experience with debugging code?
You should be able to open the project in your preferred IDE and identify the cause of that error.
It looks to me like a bracket out of place on first glance or something which would cause a cascade of compilation errors.
That's a lot of errors which likely have their root in a syntax error which is causing many other errors.
Good day everyone, Does anyone here know How to script an ingame screen panel that Tells a person's location?
Minimap?
I mean, that could be as trivial as
text.text = player.transform.position + " <-- look where I am!";
Can you explain a little further?
maybe you're looking for a panel that displays the name of the place you're in?
like "West 6th Street" or "Diner"
"screen that tells a person's location" can be interpreted in many ways
Do you have an example from an existing game of what you might be trying to go for?
Sorry my initial question was very vague currently i have a 2X3 cargo rack and im trying to create a Screen Panel that can track if theres is something wrong with one of the cargos in the rack, there would be random events that will flag the cargo
Not really, above my text is the Description
I've been trying to take a TextMeshPro and send it to a render texture without using a camera, I read somewhere that it could be done. All I managed to do so far is display the whole glyph on the rendertexture, which is a start I guess.
void Update() {
// Works to display the whole glyph.
renderTexture = new RenderTexture(1024, 1024, 24, RenderTextureFormat.ARGBHalf); // Adjust size as necessary
renderTexture.Create();
_sdfMaterial = textToDisplay.fontMaterial;
var rendrTexture = RenderSDFToTexture();
var screenMaterial = UnityUtility.CopyMaterial(screenQuad.GetComponent<Renderer>().material);
screenMaterial.SetTexture(InputVideoProperty, renderTexture);
screenQuad.GetComponent<Renderer>().material = screenMaterial;
}
RenderTexture RenderSDFToTexture() {
RenderTexture activeRT = RenderTexture.active;
RenderTexture.active = renderTexture;
GL.Clear(true, true, Color.clear);
Graphics.Blit(null, renderTexture, _sdfMaterial);
RenderTexture.active = activeRT;
return renderTexture;
}
According to that post I should use Graphics.Blit or a similar method to render the SDF material’s output to a render texture in HDR, not capturing the textmesh with a camera to a render texture. I should be able to use the Distance Field material from my TMP object to render to a texture.
huh
I have some images that seems quite pixelated when playing the game (on left scene editor they seem fine, pixelated on right)
because you're zoomed 1.5x
also not a code question #💻┃unity-talk
How I can have the script the a prefab, when this launch an event for other gameobject?
" the script the a prefab," huh?
Yeah
Can you try rephrasing your question in a clearer way?
explain please
can anyone rate my code and optionally say what i could do to make it function better (and/or better to look at)?
https://paste.myst.rs/h68h3gzr
Why abbreviate something like JFHandler
i think it's pretty fine overall, the consistency of naming and style is a little all over the place tho (some public fields are CamelCase, others are _lowerCase, etc)
also I'd watch out for using AddForce in Update(), I believe pretty much any time you are adding force on a per-frame basis (even with velocity change), you should be doing it in FixedUpdate(). You also aren't using deltaTime in your AddForce calls which would be a good idea in case you ever change the fixed timestep
note that you'll have to re-balance all your force values once you incorporate dt
i could merge JFHandler with JumpHandler if i think of that now...
I agree that AirTimeHandler should be called from FixedUpdate instead, since you are adding a continuous force there
they are using it, but not for every call to AddForce, as Osmal pointed out
oh yeah ok forget im blind today
question if i have X 3d points if I was to add them all together then divide by x it would return aproximately the center of the 3 points right?
it would return the 'average' of the positions which depending on what you think of as center is probably close enough!
Not sure what chat this should go in but, when the camera is zoomed in a lot, 24x, low fov. the looking around becomes choppy, like im watching the dpi of my mouse or something. any way to get past this so it is just as smooth as say 90 fov. using a dual render scope shader
Yup that is correct
The prefab have a script, the script shoot a event for those gameobjects, but the prefab is instance to scene thanks to other gameobject
So, I need the script of prefab for the event in the hierarchy
is this an editor scripting ? idk what you mean forthe event in the hierarchy
The gameobjects suscribted an event need the script the gameobject shoot the event
why not just pass it as part of the object or in the event handler
are you using Action?
No
which event are you using then ?
Event and delegates
Action is a delegate
are you using Unity event or C# event
C# events
so what is the issue getting the caller just use the delagate
it also has one for sender if you use EventHandler
So, is better use an Action and Eventhandler
what ? no those are both delagate types, you use one or the other
isnt that delegate you used ? EventHandler ?
Just post your code at this point lol
Do you want see my code?
@rigid island ```C#
using Unity.Burst.Intrinsics;
using UnityEngine;
public class Enemy_1 : MonoBehaviour
{
public float speed;
Rigidbody2D rb2D;
public float points;
public delegate void UpdateUI(float points);
public event UpdateUI UpdateUIPoints;
[SerializeField] GameObject burst;
void Start()
{
rb2D = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
rb2D.AddForce(Vector2.left * speed, ForceMode2D.Impulse);
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "bullet_ship")
{
speed = 0;
UpdateUIPoints?.Invoke(points);
Destroy(gameObject);
Instantiate(burst, transform.position + new UnityEngine.Vector3(0f, 2.06f, 0f), Quaternion.identity);
}
}
}
The script of the prefab
you probably can just use action here if no value is returned, also if you want make it a tuple or struct
Action<MyCustomObj>its neater than doing Action<GameObject, float>
I get it, thanks
public event Action<(GameObject sender, float points)> MyTupleEvent;
tuple is okay for 2 items maybe 3 but looks messy as hell
I like to always make my own custom delegate types 😛
btw other.gameObject.tag == "bullet_ship" btw its better to use CompareTag just a micro-optimization but ya kno
Ok
Would make more sense to move the arm with rigidbody forces or joints instead
I don't understand the part where you store the start position: startPosition = handRigidbody.position;
position is in world space
Well most of it doesn't make sense to me. Usually people do this kinda stuff with ConfigurableJoints/CharacterJoints
Also that's a weird attitude you have there lol
Whats my issue here? I try to figure out wether or not my mouse is inside a 2D Rect with this
You showed the error but what is the code?
It expects a Vector2, you gave it a Vector3
Actually that should be fine
So show your code
if(RectTransformUtility.RectangleContainsScreenPoint(targetUI, new Vector2(Input.mousePosition.x, Input.mousePosition.y), mainCamera))
{
OnDroppedOnTargetUI();
}
I put my mouse over the panel but its still false
Maybe I have the wrong approach but to me this looks like it should be working
what render mode is your canvas set to? maybe dont provide a camera for the 3rd param if you're using screen space
The error said you had vector 3 when it occurred. You've got a vector 2 now that should be valid (assuming this is where the error actually is).
As for the behavior, you'd need to make sure that both the rect and point are within the same coordinate space.
Screen Space Overlay
From what I saw online, it should work if you dont provide a camera then
It appears to also work when changing screen space to camera didnt try giving a null argument
You dont need to provide it null, the docs show there is a declaration that only takes 2 parameters
It being without the camera
How can I predict based off of a vector how far a rigidbody is gonna travel? I'm trying to calculate based off of a move direction where a rigidbody is going to end up in the next physics step
I tried multiplying (rigidbody.position + moveDirection) by Time.fixedDeltaTime but it wasn't exactly accurate
Multiplying velocity by the fixed time step would yield the delta (add this value to your current position)
Ohh thank you!!
Oh wait isn't that what I tried?
I just found out fixedTimeStep is Time.fixedDeltaTime
it's a little unclear but it sounds like what you tried was (position + moveDir) * dt instead of position + moveDir * dt which is very different
I'm trying to get how far a rigidbody is going to move in a step based off of its velocity so I definitely should've worded it differently
My whole issue here is I'm basically raycasting down and having a capsule float above the floor as it's a tried and tested movement system. What's happening is it's finding how far up it should float but because it's calculating how far up it should float as if the rigidbody is static (it's not taking into account the velocity) the rigidbody floats lower than it should when moving up a slope and floats higher when moving down a slope
you might need to simulate this inside a separate scene for Physics simulate first then grab result
So much for a physics controller lmao. It's a shame this is annoying as it is
I'll probably explore other options before that but if it comes down to that then I guess so be it rip
Sorry to interrupt. My player has a child gameobject that acts as a pivot point for a weapon and has a script that handles rotating a weapon using the mouse (it faces the direction of the cursor). The player and the weapon both have a rigidbody, but the weapon's rb is kinematic. I'm trying to have it so that when the sword hits the wall, the player will be pushed back - somewhat similar to how you move around in Getting over it. The problem I'm having is that the weapon doesn't seem to cause any collision with the wall, I expected it to cause the player to be pushed back but the weapon instead just goes into the wall. I'm guessing it's to do with how I'm handling the rotation of the weapon, maybe because I'm just setting the rotation of the parent of the weapon?
public class WeaponController : MonoBehaviour
{
[SerializeField] Camera cam;
void Update()
{
Vector3 mousePos = cam.ScreenToWorldPoint(Input.mousePosition) - transform.position;
transform.rotation = Quaternion.LookRotation(Vector3.forward, mousePos);
}
}
you definitely should not need to simulate in another scene, you can use rigidbody.linearVelocity to get the current velocity (per second), using that you should be able to predict the next frame's position (excluding any collisions)
this might be more of an issue of how you're moving the rigidbody when it's on a slope. Are you trying to make a kinematic character controller type thing?
Typically you'd need to calculate the slope's tangent direction and move along that vector, rather than straight forward
guys, can someone help me with new playstore policy. How can i get out from internal test, what should i test and how to test it i kinda confuse
if you move straight forward when on a slope you'll run into the issue where the character kind of 'falls' down slopes rather than walking down them
hey, everyone. can anyone tell me if Jetbrains Rider editor is better than vsCode editor for unity projects? looking for someone with personal experience using both at some point in time. thanks
i actually just switched to Rider from vscode after several years of using vscode. Sadly it is a lot better, I loved vscode but it seems to have become increasingly buggy with its unity/c# integration to the point where I didn't find it to be usable anymore
why sadly? sounds awesome...
i just didn't want to switch haha
or pay for a code editor, but it really is worth it I think
Isn't there a free tier for Rider now?
there is but only for non-commercial use
ah i see
lol, yeah change can hurt the soul, but change usually implies improvement. so I'd be happy if i were you lol you just made me want to switch IDE
It's a completely physical character but I'm adjusting the velocity to have it instantly snap to a height above the floor. I tried projecting the vector onto the slope but this causes some weird horizontal movement (looking slightly left on a slope moves you more to the left than looking slightly left on flat ground would) and isn't exactly what I'm going for I don't think. I'm assuming that I have to do some form of world space movement like I am now because going into source games (basically the movement I want to replicate) shows that you'll shoot up a slope instead of moving up it slowly which is what projecting on a plane would do
when you run it the first time they have an option to configure most of the hotkeys to be vscode-like
yes, i was going to tell you that if that was the reason for being sad in your case.
it definitely still takes some getting used to and it feels a bit more heavy weight compared to vscode but overall its worth the switch
what is one thing, that is clearly way better about rider for you?
one would be that it knows about unity event methods like Update() and marks them as such, it also is aware of serialized fields and you can see which ones have been modified in which assets in the code view
it also automatically recompiles in unity when you save instead of waiting for you to focus unity, so half the time unity is already done compiling before you alt tab back
you have to pay if you are using it for commercial purposes
commercial purposes? like if i've released a game using it?
if the game is not free, yes
ahh i see
i'm not sure of the specifics of the license, there might be a rev cap or something i'm not sure
do you know if you can use the free version all the way up to release of a game and then switch if you release it as paid game?
i think projecting on the plane (then normalizing) is probably what you'd want for the slope movement
it might be worth referencing the free Kinematic Character Controller package, it's really good and might be a helpful reference or starting point
it handles everything like smooth movement up a slope etc
i'm honestly not sure, but for small scale use i'd guess you're probably fine
I don't think it's exactly what I want because I have different needs but I'll absolutely give the controller a shot. Is it a thing made by Unity? Free Kinematic Character Controller seems like a really vague term
that's what i was thinking. ok thank you for the help
I stand corrected there's only one result
fwiw I initially resisted using something like that because I want very precise control over how my player movement works but that package is really well written and is very low level, it doesn't really have any impact on the game feel of your controller
the stuff it handles like standing on moving platforms and correct sliding against walls / slopes is tough to get right and nice to just have all working from the start
That's same with me. I'm probably gonna end up only using it as reference
This is partly why I wanted to make my movement all physical. Everything like that is handled for me
Such a shame that literally everything works aside from some stupid issue with slopes lmao. Hopefully I can find the solution in the controller
Hi all! I'm working on a Bloons Tower Defense-style game and need help debugging an issue with my "excessDamage" feature.
Currently, when you destroy a strong enemy, it spawns the next strongest enemy at its location (e.g., Yellow spawns Green, Green spawns Blue, Blue spawns Red). This works perfectly.
I tried adding excessDamage (e.g., if an enemy has 100 HP and takes 150 damage, it spawns the weaker enemy with 50 less health). However, my implementation breaks the "SpawnWeakerEnemy" logic, and no weaker enemies are spawned. The enemy is just destroyed outright.
Not Working Script (has excess damage): https://paste.mod.gg/nrbtsglmuxns/0
Working Script (no excess damage): https://paste.mod.gg/hbygerqlalwg/0
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
I see you have debugging log statements in there - what was the result of that?
One moment, will run it and screenshot for you. But will say, during one of the attempts, the debug logs indicated that the weaker enemies were indeed being spawned but instantly destroyed for some reason.
I mean one simple quick thing I'm seeing is that you're not making any attempt to spawn a weaker enemy at all unless there is excess damage:
if (excessDamage > 0)
{
SpawnWeakerEnemy(excessDamage);
}```
Wouldn't you spawn the weaker enemy no matter what, and just apply however much excess damage there was to it (including 0)?
Yes, that clearly is an oversight on this most recent attempt. Ill fix that and let you know if that was the issue here
I removed the if conditional and am calling SpawnWeakerEnemy no matter what. Its still not working but I'm noticing some weird activity: from the debugs you can see that it looks like the enemy is being spawned. Also, for example, when my turret destroys a blue enemy I'm seeing blue particles (from its death effect) but also red particles (from reds death effect, blue should have spawned red). Indicating that, for some reason, the new enemy is instantly being destroyed
To clarify, the blue death was caused by a 100 damage projectile when blue was at 100 health, so expected behavior would be that blue spawns a full health red.
Yep time to debug why. Starting with a log in the TakeDamage function
I updated TakeDamage and SpawnWeakerEnemy with new debugs and the issue persist, but the logs are mad confusing. Red spawns, instantyl takes 0 damage, instantly 0 remaining health? Which trigger its dying debug, but then after it says red is spawning with 100 health?
Could the order these debug logs are occurring be indicative of the issue? As in, there being a slight delay in the spawned enemy getting its health set, and during that delay, the game registers it as 0 health and destroys it?
the game registers it as 0 health and destroys it?
Not unless you have code that does that in Awake or OnEnable on the enemy class
Which you don't
I do see that the red enemy is just never being given health
Oh I see why
it's because you're not assigning the health until Start
void Start()
{
_health = stats.startHealth;
_speed = stats.defaultSpeed;
}```
that's much too late
you should delete this Start function and just make a function to set the stats:
public void Init(EnemyStats stats) {
this.stats = stats;
_health = stats.startHealth;
_speed = stats.defaultSpeed;
}```
And then instead of:
Enemy weakerEnemy = enemyPrefab.GetComponent<Enemy>();
weakerEnemy.stats = weakerStats;```
you do this:
Enemy weakerEnemy = enemyPrefab.GetComponent<Enemy>();
weakerEnemy.Init(weakerStats);```
I would also change this variable name as a matter of suggestion:
GameObject enemyPrefab = Instantiate```
That is not a prefab
when you instantiate it, it's an instance
something like newEnemy or enemyInstance would be more appropriate
prefabs are only the things that live in your Assets folder
they never exist in the scene
Three hours i spent trying to troubleshoot this and I can't believe I never considered removing health from start. Wow.
Start isn't going to run until like, the next frame after you instantiate
Does this mean I don't need Start at all anymore
yes
Assuming you always call Init on a newly spawned enemy
You could also do:
void Awake() {
if (stats != null) {
Init(stats);
}
}``` so that enemies placed in the scene directly instead of instantiated get their stats assigned properly
Uh, I'll have to check my RoundManager to see how the waves are spawned in. I'll leave start there for the time being till I determine the manager is reliant on it
Generally speaking, what would be the recommended approach
well leaving start there could be problematic in that, if you have excess damage, and then Start runs after, they will heal
Oh true, okay I'll check on RoundManager right now and make sure everything is setup to handle either Awake or Init
It kinda depends on how your game works.
If I made a game like this I would probably just have each enemy prefab just have their stats assigned in the inspector and this wouldn't be necessary at all.
But if the stats all need to be calculated at runtime then something like the Init method with a fallback in Awake would be about right.
You could have a bool that stores whether this enemy's stats have been initialized yet or not, to safeguard against accidental initialization.
Still stuck on this - anyone have any ideas?
You are directly modifying the object's Transform (in this code its rotation) which means it's not going to play well in any sense with physics.
Likewise - unless that sword has a Rigidbody, it will not be applying any forces to anything.
So is it just a case of getting the rigidbody of the child gameobject (the weapon in this case) and rotating that instead?
something like this would require essentially two Rigibodies attached to each other with joints
not a parent/child relationship
ohh i see
and they would both need to moving purely via physics
@leaden ice Just finished implenting your suggestions and testing it. It works perfectly! I can even skip enemy types ie dealilng so much damage it jumps a level like yellow -> blue instead of yellow -> green -> blue. Thank you very much!
As to your suggestion about having the stats assigned in the inspector. Mine are attached to scriptableobjects, is that not a good approach?
that's fine as long as they're immutable
Thanks for your help, will have to tweak it to get it feeling right but this is exactly what i was wanting :)
How hard is it to convert a line renderer into a mesh?
It's already a mesh though. It generates a mesh I mean.
Didn't realise that. Would it be difficult to add depth to it?
Depends on what you mean by it
I'm using a line renderer to create a laser, but the billboarding looks weird and I would rather it just be fully 3D
It depends entirely on how comfortable you are with procedural mesh generation
Haven't really done it before
if the thing is just a straight line, it would be simple enough to use a simple cylinder or capsule mesh and just scale it
it has a steep learning curve
It reflects off of walls so not entirely straight
Wdym by fully 3d? Like a tube mesh?
Yes exactly
Honestly it's usually not that hard to improve the look of LineRenderer with some shader or other rendering tricks. Probably not worth the effort to get into procedural mesh generation. But, the answer is "hard, especially if you've never done anything like it before"
Honestly, I wouldn't use it for a laser, but it's up to you. Either write your own mesh generator, or maybe use splines. I think they have a tube mesh generator included.
They do but I'm not sure if it works at runtime or how efficient it is
How can I use the tube mesh generator?
Do ScriptableObjects have a maximum number of allowed sub-assets?
There is no defined limit for the number of objects that you can put into a single .asset file, no. I imagine that you might start to encounter some bugs at the 2 billion mark, and performance might be poor long before that.
what are you trying to do
Id say, the memory is your limit. The more you try to load at once (unless you are using addressables), the more will be put into memory and your game will start to lag when its hitting the whatever systems limits.
ah dang my idea of having 2 billion sub assets is dead 😦 /s
I`ve been trying to set materials to a mesh and its sub mesh through code, but when I duplicate the mesh afew times the materials seem to swap without any apparent reason, does anyone know why this may be happening?
Hi does using Tasks allow multithreading for non-Unity API stuff in code or it just ends up like co-routines?
If you start them with Task.Run, then yes. If you use async awake, it acts as a coroutine.
this is not really Unity specific but gltFast uses tasks and I just want to set off the import task and get a callback on complete, but not having used Tasks I am still searching for an example!!
Just await it.
Check out the sample code in the documentation,
https://docs.unity3d.com/Packages/com.unity.cloud.gltfast@6.10/manual/ImportRuntime.html
u cant await from a normal function though - the example has all async calls
I need to start from a non async function!
Make the non async function call an async one where you can await, or use .ContinueWith.
Then make an async method and call it from a non async method.🤷♂️
Tasks are fundamentally callback based, async/await is just nice syntax sugar to write code as if they were synchronous so you can avoid going into callback hell.
While you can use .ContinueWith to go back to writing callback based code with tasks, that's like going backwards.
As others have said, you can await a task in an async function. If this is editor code you can stick with Task else use UniTask or awaitable in newer unity https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Awaitable.html
yes but I am trying to compare to StartCoroutine(xxx), (then it ends current function). I must be confused how to do same with a Task. If you run one without await does it then continue the function?
Its not the same as a coroutine, the async function runs regardless of it being awated or not
so how do you achieve multi threading then?
Task.Run() to execute the code on another thread (or UniTask equivalent)
you cannot use 99% of the unity apis on other threads so dont bother (it will just throw an exception)
https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.run?view=net-9.0#system-threading-tasks-task-run(system-action)
packages probably work but again if they interact with say AssetDatabase it will probably break (attach a debugger to break on exceptions to know if this happens)
yeah I find it odd gltFast went with the Task approach - not sure of the reason as Tasks are not seen anywhere else in Unity
just to throw another option out there, in recent versions you can do await Awaitable.BackgroundThreadAsync(), which will resume after that statement on a worker thread for pretty much the same effect as Task.Run
Tasks are quite common. But you don't need to use Task.Run.
İs it possible to add a Destroy call here?
I use UniTask as i mainly work in older unity such as 2022 where Awaitable did not exist.
You can just run it normally on the main thread. If the plugin code is good enough, they would run the heavy stuff on a background thread themselves.
ok so I can just do bool success = import.InstantiateMainSceneAsync(obj.transform).Result;
If you implement an instance method in your script that calls destroy, sure.
So i gotta create a sceipr?
İ thought it would be possible to xall Object.Destroy dkrectly
Yes, you can.
It would block though
.Result will block that thread.
don't do that unless you know InstantiateMainSceneAsync only runs on another thread, that's a fast way to freeze your game
if you block the main thread waiting for the main thread nothing is going to happen
Destroy is a static method.
Ok ty
well exactly guys - so if I want to start off the InstantiateMainSceneAsync from a non async function and not block anything - what is best way?
If you for some reason really don't want to make an async method to use await, use .ContinueWith, when people have no issue making a separate method so they can StartCoroutine. But if you really don't want to, that's the way.
make an async function and await it
plz just read up on async this is not going well 😆
The way they do it in the example.
you can use async void , it's safe in unity
ok but how do I call the async that calls the asyc instantiate call? (sorry I am Task beginner it seems)
you call it as a function but dont await 😐
As a normal method.
async void Start() {
var success = await import.InstantiateMainSceneAsync(obj.transform);
}
void Start()
{
DoThing().Forget(); //Forget is a unitask thing to log errors properly
}
async UniTask DoThing()
{
await UniTask.Yield();
}```
Just this should work
void Start()
{
DoThing();
}
its shit though
the example returns a value, presumably they want to check the success
for runtime game code you don't want to use Task
void Start()
{
DoThing();
}
async void DoThing()
{
//the async logic
}
to be clear, Task is the .net async task object, UniTask is a unity specific replacement for Task that is better for Unity specifically.
and Awaitable is the same but made by unity but ONLY in later unity versions
well my situation is at some point in game (well app) a few glbs will need loading, So if they can be started off and later I get a call to say finished, would be good
async void is bad as it uses Task anyway which you want to avoid.
Why would you want to avoid it..?
where is the task? 🤔
god i just explained
There's nothing wrong with using .net Tasks.
async methods are async methods, whether you're using UniTask or C# tasks, and neither one is being used if you use async void because... it's void haha
Task creates garbage. async void actually uses a Task behind the scenes but this syntax means "this function is not awaitable"
UniTaskVoid exists to replace this too
https://github.com/Cysharp/UniTask plz read
There's nothing bad in a little bit of GC.
all async methods create garbage because it has to allocate a state machine on the heap, UniTask and Awaitable are just more efficient because the return object is pooled or a value type
that's a C# thing, not a Task thing
Yes. UniTask also offers functions to let you properly interact with unity frame events just like coroutines.
They explain it on their github page readme.
you can await several things in a row like this if needed, and any code you put after the awaits will happen when they're all loaded, is that what you mean?
Here is a full example from me of an async function to do some animation:
https://github.com/rob5300/UniTaskDemo/blob/main/Assets/Scripts/UniTaskDemo_CancellationToken.cs
yes but I find it odd every Task example starts with an async function - if I can just call such a function and immediately continue current function then its ok - otherwise I am lost as await will just block
I think it's helpful for you to learn what task and async/await is about before you attempt this. "Start it now, call me back when you are done" is exactly what task is.
if you want it to act like a coroutine, make a separate async void function, and when you call that it won't wait, just like StartCoroutine
or use Forget or whatever
yeah that would work - because at end of day unity code completely different and a Task could take a while so I do not want to wait - not for the first call
example of not waiting for async function: https://github.com/rob5300/UniTaskDemo/blob/main/Assets/Scripts/UniTaskDemo.cs
Asynchronous actions fundamentally completes later, tasks is just an abstraction for this "start now, call me back when you are done" pattern:
void SomeMethod()
{
StartATask().ContinueWith(result =>
{
// Do something with the result
Debug.Log(result);
});
}
This code sucks to read and sucks to write, so C# comes up with async/await, which allows you to rewrite the code above into:
async Task SomeMethod()
{
var result = await StartATask();
// Do something with the result
Debug.Log(result);
}
This syntax sugar makes the code nicer, but behind the scene it does the same thing.
Just because StartATask returns a task, it doesn't mean you have to use async/await, you can just use .ContinueWith.
But again, I don't understand the obsession to "avoid making an async method."
sometimes you dont want the function to be async (e.g. using ref/in/out)
anyway its flexable and its nice. I use ContinueWith often to add a result to a list and still await it.
I don't mean "making the method async" I meant "making an async method"
wa
If for some reason you cannot make the method async (eg ref like you mentioned) but you still want part of the logic to use the nice async/await syntax sugar, you can move that part of the logic to a separate async method. Or if you are using UniTask, move the logic into UniTask.Void(async () => { ... }).
actually is this _ = LoadBinaryTask(data, r); //run and continue the same as .Forget();?
You can do await LoadThingy().ContinueWith(thing => things.Add(thing));
no, it discards any thrown exception and won't log an error
Yea Forget() is special to make sure exceptions are logged to the console
You might as well just write:
var thing = await LoadThingy();
things.Add(thing);
errors thrown in an async void method are also logged by unity fwiw
And I suspect whatever things.Add(thing) is doing, can be better accomplished by friends like Task.WhenAll etc.
you are right you get back all results, but ContinueWith() lets you react for that task when its done and still await after.
.ContinueWith has its place but it's very rare in modern code. Often time it's much easier to write the equivalent in async/await.
look its just another option do u
it gets pretty messy when you mix callbacks and async await
the difference with ContinueWith is it doesn't guarantee you're continuing on the calling thread like awaiting a Task does (no idea if UniTask guarantees this, Awaitable doesn't last i checked, so there's still a use for Task sometimes)
~~no async code guarantees this but ~~Unitask ofc offers things to help ensure you are on the main thread
C# tasks do
Hm didnt know this, cool if it does!
unless you use ConfigureAwait(false), awaiting a task never results in you resuming on a different thread
you can use await UniTask.SwitchToMainThread() to make sure you execute on the main thread
Awaitable also allows awaiting the main thread switch.
ContinueWith has a TaskContinuationOptions argument where you can control which thread the continuation runs with.
im stuck on 2022 so UniTask is all i get
I'm on 2022 as well and uses UniTask, I'd probably still stick with that even after migrating to 6. The cancellation situation with awaitables seems less than ideal.
all the methods do take one
I like unitask too. I use UniTaskCompletionSource a lot as well as WhenAll() and WhenAny()
Awaitable itself has a Cancel method, i have no idea what that's for
Aren't awaitables pooled and thats why you can cancel them? Because every instance of an awaitable is unique to the current task?
UniTask is the same unless you use Lazy
is that it? i've always just used a CancellationTokenSource
hi, guys. how can i access surface type field via script (urp)?
This is a material
Hold on
This is lit default right?
Surface Type is a bit weird -- it's not a single property on the material. It configures several different properties of the shader.
I'm not on pc right now but we need to look at a copy of lit default shader for this
(well, everything in the "Surface Options" section is a 'bit weird' in the same way)
It would be more optimal if you created another material that has the settings you want, then change the materials as you need
This is slightly tangential, but I know you cannot change these sorts of properties at runtime in the built-in render pipeline
(e.g. you can't change Stencil settings)
this has caused me enormous amounts of pain in VRChat
I'm pretty sure you can, but you need to look at the original shader's property's name because the display name in the editor is different from in the shader
But yes it's an immense pain
like Base Map in editor is actually m_BaseMap when you GetTexture
yep, i think that is the best way after what you have said)
I'm actually not sure where you'd read about what you can and can't change at runtime. Most of my knowledge comes from bashing my face into a wall and reading the docs for Poiyomi Toon, lol
I don't have a lot of experience working with shaders
The 2 times that I do I writhe in pain
Unity's (URP) shader workflow hurts my brain
The people in #archived-shaders can help you better
What is it that you want to achieve anyway?
In gameplay terms
Surface Type actually controls many things
opaque/transparent is a major change and should not really be necessary at runtime.
notably, changing it on an HDRP/Lit shader changes:
- ZWrite
- Several stencil settings
- The blend modes
- Several keywords
- The render queue
You can do very funny things by writing shaders that don't fit cleanly into an existing surface type
Why not just swap out the material ?
@heady iris I hope you don't mind if I copy paste some stuff from your GUID constructor, it's got a lot of code that I don't deal with regularly like getHashCode() or Equals().
Most of that is itself copy-pasted from the blog I had linked :p
the circle of life
(and I think that mostly just mimics what Unity's GUID class does)
notably the GetHashCode method
it appears to use the standard technique: Multiply your numbers by a prime number
i remember making that up in high school lol
(why? because prime number are..."more random" in some vague sense)
Did u log ?
(might be an #↕️┃editor-extensions question)
is there an easier way to have multiple variables have the same attribute
so my code doesn't just look like 
Where ? N show it printing in console
I would say this picture is best practice.
(possibly an #↕️┃editor-extensions question because i need it for a custom attribute anyway)
But you can certainly do:
[SerializeField]
private int a, b, c, d, e;```
oh right, i completely forgot i can do that
i put logs into new script that searches for the navmesh, and that logs just fine, but i dont know why it would not work in buil, isant there something in project settings?
Hello, im trying to Load an addictive scene, i have 3 scene Demo, UI and Game. and im trying to load the UI and Game from Demo scene. but i got NRE?
i alredy put the scene on buildsettingg. appreciate any help thank you
https://hastebin.com/share/nuwiwerinu.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i got NRE?
Where?
Be less vague
Also note thjat:
!SceneManager.GetSceneByName(sceneName).isLoaded``` this is probably not correct
GetSceneByName only works for scenes that are already loaded.
why would it be in the project settings? its unclear what you did and didn't do, without seeing it I have no idea
Also:
AddictiveScene 😮
what is addictive supposed to describing here?
pretty sure it's a typo - should be additive?
oh, that makes a bit more sense. still dont know what it means but i can guess from context
yes i got NRE on this code
// Got NullReferenceException: Object reference not set to an instance of an object
SceneManager.UnloadSceneAsync("Demo").completed += operation =>
{
LoadAddictiveScene("Game");
LoadAddictiveScene("UI");
};
you cut off the most important information in that error
namely the filename and line number
im sorry got typo there. thank you for pointing out
when showing an NRE this is important part to share.
https://unity.huh.how/runtime-exceptions/nullreferenceexception/stack-trace
i would assume the SceneManager is causing the error, i dont think anything else in the function can even be null
well its probably UnloadSceneAsync("Demo") not finding Demo, and probably cannot be accessed by .completed prop
yes you can't do .completed += on the invalid scene
oh good point. i've never used the async scene loading before 
i already put the demo on BuildSetting..
Yeah but you can't UNLOAD a scene that is not already loaded, presumably
maybe just Debug.Log it to be sure ?
aaah i see, thank you. i'll try another way then. have a great day!
Scene currentScene = SceneManager.GetActiveScene();
// Got NullReferenceException: Object reference not set to an instance of an object
SceneManager.UnloadSceneAsync("Demo").completed += operation =>```
You should be unloading `currentScene`, whatever it is. Not hardcoding "Demo"
yeah finding hard to belive i got nre so i try hardcode it to see whats wrong with it 
I'm making a UI system, made of pages
So I have a
public void OpenPage<T>() where T : UIPage on my UIManager
which destroys the currently open page, and instantiates a new one from a Dictionary<Type,UIPage> of page prefabs
I have a list of all page prefabs inside a scriptableobject, to which I add all my pages through the inspector, but I'd like to be able to choose which page goes first, from inside that same ScriptableObject
and I'm not sure how can I create an in-inspector selector of a specific page, so that I can just open it through the OpenPage<T> function
I'd rather avoid using reflection for this please
do I have to create a separate OpenPage(Type pageType) or is there a nicer way?
This is ugly, as it doesn't have that nice compile time check that PageType derives from UIPage, that OpenPage<T> does
Why do the pages need different types?
I would put any differing functionality on separate scripts
let the page component just be a single simple type
GameObjects can have multiple components for a reason
because then, from within a button that opens settings for example, I can just do uiManager.OpenPage<SettingsUIPage>() and it magically works
and if they weren't different types, I'd have to figure out some other way like string keys or integer IDs and I really don't wanna do that
And since I have a guarantee of never having mutiple prefabs for the same thing (so no doubling up on the Settings Page prefab for example), if every single one is a different script deriving from UIPage, I can extremely easily open them at will, with easy compile time checks that I'm not trying to open something silly like a plain monobehaviour or something
Unless I'm overcomplicating and missing something obvious here?
You could do this with the "separate" components too - if you map the type of the separate component in a Dictionary somewhere.
what algorithm can i use for triangulation for a set o points in 3d that represents a surface?
yea but what exactly are you suggesting then? I mentioned that I'm already mapping those types deriving from UIPage in a dictionary, to their prefabs