#archived-code-general
1 messages · Page 373 of 1
[System.Flags]
public enum Weaponry
{
Gun = 1 << 0,
Melee = 1 << 1,
noGun = 1 << 2,
noMelee = 1 << 3
}
Something like this yeah?
I don't think you need the "noGun"/"noMelee" variants here, you can just check if "Gun" or "Melee" is not included in the flag value. Unless I'm missing something?
Lemme read your previous convo a bit
Anyway, you can think of enum flags functionally as an "array of booleans", specifically 32 bools when it comes to 32 bit integers which is the default. One boolean for each bit.
You wouldn't check if you do have a "noGun" flag. You would just check if you don't have a "Gun" flag
The way I see it, filtering it by unknown/has/not can be achieved with using two enum values, an require-enum and disallow-enum (both are instances of Weaponry). Any one that the player ticks "has" is added to the require-enum, and any one that the player ticks "doesn't have" is added to disallow-enum. For instance, player wants to find someone that has a Gun but not Melee, then requireEnum = Weaponry.Gun and disallowEnum = Weaponry.Melee. Then, to filter each element, you'd check both enum values against the actual instance: ((value & requireEnum) == requireEnum) && (value & disallowEnum) == 0).
((value & requireEnum) == requireEnum) checks that all the ones you're requiring are all present in the element.
(value & disallowEnum) == 0) checks that all the ones you're disallowing are not present.
Any others that the player didn't specify as required or disallowed (ergo, unknown) won't be considered.
Yeah but the reason i put "noGun" is because i'm sorting my list trying to find a criminal, and they tick things off based on what they find, so if they find a gun you tick guns, but if they can't find a gun you "cross it off" and that evidence comes up as "noGun" because they couldn't find the gun anywhere. And checking if i don't have a "Gun" flag is just saying they haven't found one yet
Okay I see, makes sense to have separate flags for that then.
It's like the phasmophobia evidence journal if you've ever played that
I haven't, but I see your idea
So this should be good
What about this one?
I say it's a bit of a code smell to have that, using two enums would be cleaner and not require you to duplicate every flag
Maybe separate the "already checked for a gun/evidence" state from the "found clues" state.
How would I make it not a code smell?
I'm not sure what you mean aha
Don't add any "noX" entries, use the pattern of having one set of stuff that user requires the thing to have, and one set of stuff that the user requires the thing to not have. This is a question of selection and filtering a list, is it not?
Actually this also seems like a decent way to do it yeah. Especially if you have more than a few flags
Well, right now you use that enum to both determine if a clue was searched or not and what clues exactly were found. It's like putting two separate things in one.
Yeah selection (Unkown, yes, no), and then filter my list of criminals based on what is yes, or no basically
OK, so there's also another way to use two enums then, based on what dlich said: a mask for which clues you're sure about (exists/not) and a value for whether each given clue was present or not. Both are valid, and I really think thinking along these lines is cleaner than copying each flag with a "no" counterpart
Does anybody have strong opinions on naming variables according to "deceleration" or "acceleration"? I have variables which will only be used when decreasing a speed, and I'm never sure if it's cleaner to always refer to them as one or the other, and whether it's cleaner to negate them when used in a calculation or just set them to a negative value on assignment
Rather than this then, how would it look based off of what you're saying? @timber finch
Since I described the way of using separate enums for require/disallow, I'll describe using "checked" and "found" enums.
[System.Flags]
public enum Weaponry
{
Gun = 1 << 0,
Melee = 1 << 1
}
// evidence types user made selection for
Weaponry checked = 0;
// whether each selected type was found or not
Weaponry found = 0;
// add user's evidence choices from wherever
foreach (var evidence in allEvidence)
{
AddResult(evidence.weaponType, evidence.found, ref checked, ref found);
}
// original list
List<Crim> crims = ...;
// filter down by the entries that match the user's choices
IEnumerable<Crim> selectedCrims = crims
.Where(
crim => (crim.weaponry & checked) == found
);
// helper to add flags for the result of checking
void AddResult(Weaponry weaponType, bool isFound, ref Weaponry checked, ref Weaponry found)
{
checked |= weaponType;
if (isFound)
{
found |= weaponType;
}
}
@solid relic @timber finch thread please
Not entirely sure what you mean. Can you provide some examples?
I'd just have an acceleration and some accRate/decRate if the two rates differ.
Since I described the way of using
Not sure if this is a bug with the newest Unity 6 Preview or just some regular thing I don't understand yet.
When I'm registering a callback <KeyDownEvent> to a TextField (UI Toolkit) there is always a second keystroke which has KeyCode.None. This thing is responsible for many "exceptions" happening when I'm trying to send messages into my chat UI via Return.
I tried to prevent that keystroke and return early before it goes down the road but now I can't write anymore so I suppose it's needed to display the character in the field.
Is there a way to solve this or do I just have to accept the Exceptions following?
Code:
_messageInput.RegisterCallback<KeyDownEvent>(evt =>
{
if (evt.shiftKey && evt.keyCode == KeyCode.Return)
{
_messageInput.value += "\n";
evt.StopPropagation();
}
else if (evt.keyCode == KeyCode.Return && !string.IsNullOrWhiteSpace(_messageInput.text))
{
OnSendButtonClicked();
evt.StopPropagation();
}
}, TrickleDown.TrickleDown);
I'm making meshes with code, but when i try to apply a material or a texture to them, they turn into one solid color. After some testing, i realized this is because the texture is incredibly zoomed in on these objects, i can use the "texture offset" to see the whole texture. Is there anyway to "zoom out"?
You probably don't have the uvs assigned correctly
i fully believe that, how do i do that?
In a similiar way as you assigned the vertices, but with a list of Vector2's and SetUVs
What would the vector2's be?
The UV coordinates. They tell the shader what part of the texture goes into what part of the mesh
So you've verified that the keycode that's throwing the errors are with the KeyCode.None? Can you show your implementation with the early return and a log of the key before the error occurs?
Yes they came from KeyCode.None. Altho I solved that issue now by not only empyting the messageInput.value but by also resetting the cursorIndex and selectIndex to 0. Then the ArgumentException is gone.
Now however I have the issue that the "rewriting" of keybindings for a new line (Shift + Return instead of Return) is not "overwriting" the default behavior..
Hey all! Would someone be kind enough to help me with an error I am having regarding accessing a function from a script into a ScriptableObject script??
Provide relevant error messages with stack traces.
When i load another scene from the main one i can t move in the loaded scene, but if i load it when the game is stopped and i play it works. Do somoune know what it can be?
Do you have any errors in console? Kinda hard for anyone to say without more insight to what you're actually seeing
no i don t
I know is something from the main scene because i use the same script to load other scene and it works perfectly.
Well then you'll have to start debugging why you cant move, or at least start showing relevant information.
Still I dont think it's possible to suggest anything based on so little information of it just not working
i can tell you what i have in the main scene maybe?
i ll send a video i have to commpres it first
🤷♂️ if you arent even sure what to share then start debugging. Recreate this issue in a separate minimal scene, removing objects that dont cause errors until you find which objects are related
A video tells us nothing, you need to debug your code and then show the code and the logs
i tried going into the second scene and removing every object separetly
Hello everyone, I am making an enemy spawner which is responsible for spawning enemies in following ways: Random Spot, Triangular, Circular and Star. How can I make a enemy spawner which is easily scalable ?
Scalable in what way? This sounds like something you could just use an enum and respective method for, for each of those ways of spawning.
Scalable in the sense that when a new spawning way is added, it should not modify original class, in short I just want to follow SOLID principles, Am I overengineering here ?
Sounds like work for an ISpawnMethod interface and/or strategy pattern or smth like that
I'd say so. I wouldnt follow SOLID so deep here. The way which I've wrote will be the most understandable/easiest for someone to look into the file and just see all the spawning methods.
You could go the base class/interface method but then suddenly you're creating extra instances of objects for nothing. Also you lose out on inspector functionality. An enum is easily selected in inspector, a derived class is not.
I think you are right. I should not go with over engineering approach, I should go with enum approach.
I think you can try strategy pattern
Clear and easy to add new way of spawning
you could also mess around with some delegates. Either way i think following solid a bit is not that bad here, at least i would separate "spawner" from "available spawn methods"
unless you're 100% sure that there will be at most several of such methods, then single class with enums is ok
A delegate would just be used to link enum to method here in some dictionary most likely. It doesnt affect scalability or anything. Basically just another way to call the method
Interfaces or these patterns really add nothing other than creating more objects to do the exact same work. The user wont care that you did it "cleanly". The only argument I'd really see for it is if this is an asset and you want to allow custom spawning methods. Even then, people would likely just create their own script if they wanted full customizability for something simple like this. In reality though this is likely a solo dev project and they wont have many methods.
you're right, i mentioned delegates in terms of separation, ie having dictionary filled runtime in class other than spawner itself. Just saying that in case that there is possibility that this system will extend in the future so much that enum approach will become not enough "modular", it is good to have a plan for such situation and design code at early point. But yeah, it is unlikely for such simple thing
I had an Idea for a great Game mechanic in Unity 2D but have not Idea for a solution, basically I want to switch between 2 worlds(times) , the past and the present, and if I for example push a box in the past which is however chained in the present, said box actually stays at the exact same position in the present as in the past. Anybody have any ideas for solutions?
it is super-wide question
im not sure what you mean chained in the present, but this just sounds like a level saving kind of problem. the goal is just recording anything down in a scene that needs to be recorded.
When you go to the past or present, load up the respective data and spawn in the objects you need whereever you need them. You'll probably want base class/inheritance for custom behaviour when going to the past/present if something isnt just a matter of "move/rotate this way".
Every time I try to continously move a camera along with/attached to a rigid body the screen rubber bands a lot. It happens quite a lot of me, is there a solution/reason for that?
I tried putting the movement in Update, FixedUpdate, LateUpdate, changing/disabling the interpolation of the rb, and adding a smoothing function to the movement, but none of those have worked
With interpolation on, lateupdate should be fine. Are u using cinemachine? It has a ton of options to play around with
i have two positions Vector2 and i want to convert these two positions to a float rotationInDegrees. how would i go about doing this?
Could probably use the Angle method to create an angle between two directions.
Where one direction would be the direction of your two points (a - 2 normalized etc) and and the second some fixed direction (Vector2.right or something).
https://docs.unity3d.com/ScriptReference/Vector3.Angle.html
For examplecs var a = transform.position; var b = target.position; var dir = (b - a).normalized; var angle = Vector2.Angle(dir, Vector2.right);
Tangent: you might want to remove Time.deltaTime when acquiring mouse x and y.
thank you that worked!
was looking for a angle function in vector2 and nothing 😵💫
Vector 2 actually has Angle as well
https://docs.unity3d.com/ScriptReference/Vector2.Angle.html - accidentally linked the 3 variant.
https://unity.huh.how/mouse-input-and-deltatime @quick glade
If you were following a tutorial (Brackeys and others on the net who are using such practices), they've simply made a mistake.
No, I'm using just a quick-made script
Reminder that GetAxis with "Horizontal" and "Vertical" are fine (using Time.deltaTime) but not "Mouse X"/"Mouse Y".
If the axis is mapped to the mouse, the value is different and will not be in the range of -1...1. Instead it'll be the current mouse delta multiplied by the axis sensitivity.
https://docs.unity3d.com/ScriptReference/Input.GetAxis.html
Already a delta etc
thanks for advice, im giving look at it now
@dusk apex Thanks for the good information about axis, but there was no improvement in my main mistake.
so when i release alt key, camera or input axis whatever you say; i have to reset it to 0 but even after resetting, it goes back to the angle i was looking at when i was in alt look
(sorry for wrong tag)
The difference between the two if-statements is mainly with character rotating in alt look. What is character? Which object is it? Is it the same as the one with this script attached? I'm assuming it's some parent Transform.
this script attached to camera, character is the parent. the fact is im rotating character's Y and camera's X (works with head ik)
because the head has to be able to move up and down, so in a way the camera
I recommend using two floats to store the angle and adding the mouse input in Update, clamping it, and then setting the local rotation to those angles
Just set the parent rotation to zero when alt look alternates to false?
Remember to record the value in the case you need to use alt look again.
I do it more or less like this, but it is very confusing to have multiple devices (gamepad etc.) and up and down head movement in altlook false and true
In the code you attached it seems like the angle variable is only in the local scope, so doesn't persist between calls to the function
i want to reset camera's rotation to zero when altlook becomes zero, few games like pubg or cod etc. has this function : you press alt and look somewhere else while walking
Like in Tarkov?
yes probably
Since I don't know how it works ik pubg
i shared most basic version of function
Example:cs private Quaternion altRot; private bool altLook; public bool AltLook { get => altLook; set { if(altLook != value) { altLook = value; if(altLook) { character.rotation = altRot; } else { altRot = character.rotation; character.rotation = Quaternion.identity; } } } }Something of the sort.
And what is the issue you experience?
Also I'm confused by the use of two multipliers in the assignment of value to angles vars. Also, shouldn't it be a += operation.
Edit : read the docs about mouse axis, you'd most likely want to use a += there
Otherwise every frame the rotation would reset
All right, thanks to you both, i will take a long look to this.
it gets very confusing because there are multiple “Look” types and frankly i hate coding camera & input functions 
just use cinemachine
did you try lateupdate with interpolation on? it should be fine. maybe theres issues with the camera logic otherwise
i wish too but i need a custom thing bc of there's more than one movement & look types
Or first solve as much of the issue as you can yourself to learn how it works
I did. I'll send the code and a video of issue in 15m
and cinemachine has more options than you'll ever need. its not just one camera mode. honestly the code youve shown is like the most common camera movement there is
and you can always add your own functionality on top of it
Something of this sort?
Uncomment that one line if you want to look forward after disabling free look
This version also resets the free look between every enabling
Or that if you want it to be saved between free looks
Eventually could do
horiz_angle = horiz_angle * a;
where a is between 0 and 1
To smoothly go back to looking forward
yeah i tried it and exactly this is what i want
thanks it works
Huh?
This sets the rotation as far as I remember
If you want to rotate something from its current position, the safest bet is transform.rotarion * Quaternion
roger that thanks for your time friend 
No problem, good luck with your game
Is there a way to temporary disable any code docs without writing // next to everything? So they wont interfere when i test something else out
Disable docs? You mean comments? Comments are always disabled
If you really need to, you can wrap some code inside #if CUSTOM_MACRO #endif and either define/undefine such macro in script or player settings globally
maybe
normal code;
/* code that wont be run;
code ;
code; */
normal code 2;
no i mean like dissable a script. sorry
i have yet to learn how to close mine
that could work ill try, thanks
you can do it in the editor
The checkbox in the inspector
Thanks
Yeah, for entire script just disable it in inspector. For only the parts, comments are enough. Macros are for global things like enabling/disabling only parts of code in multiple scripts at once
Can mess up your project if you overuse them tho
(they serve another purpose than making runtime logic but a single custom macro just for testing is acceptable, just remember to clean up scripts from it after you're done)
so im trying to add a listener to the shoot action event in my input system like this: _input.actions["Shoot"].performed += UseAttack; where UseAttack is just private void UseAttack() but im getting the error: No overload for UseAttack' matches delegate 'Action<InputAction.CallbackContext>. what am i doing wrong?
Your function need to respect the signature.
private void UseAttack(InputAction.CallbackContext callback)
do i need do use the callback for something or? what does that do?
or what can it do?
Do not know, if you don't need do not use it.
Simply change your functinon to what I said.
I believe it is something about the input system.
does anyone know why EventType.MouseMove in IMGUI isn't available at runtime?
(and if there's a nice way to replicate it at runtime?)
I don't know why but according to docs it is intended 🤔
You could manually check if Event.current.mousePosition changed
yeah I was considering that, but I'm not entirely sure if I'd be able to replicate it with an actual MouseMove event so that the rest of the code responds accordingly
(the use case is that I want to share the same code in runtime and in editor for an IMGUI thing)
approximately how illegal would this be lol
void OnGUI() {
// <--- gui goes here
Event eCurr = Event.current;
if( eCurr.type == EventType.Layout && eCurr.mousePosition != prevMousePos ) {
Event eMouseMove = new() {
mousePosition = eCurr.mousePosition,
modifiers = eCurr.modifiers,
delta = eCurr.mousePosition - prevMousePos,
type = EventType.MouseMove
};
Event.current = eMouseMove;
OnGUI();
}
}```
Probably fine if you assign back the old event after, just so you dont break anything down the IMGUI line
oh yeah, prolly need to do that
it's a little scary to run the mouse event before (I presume) the layout event is finished wrapping up
right okay this is a little unstable
mouse coords are global rather than local when doing this, which I presume requires finishing the layout OnGUI
maybe this is where I give up and finally learn UITK proper 
Well the grass is definitely not greener over in UITK land but it's pretty nice when you need more advanced options to customize the UI
hmm ok
for editor scripts
UIToolkit > IMGUI
unfortunately this is a hybrid meant to be used both at runtime and in editor. the scene view, specifically
I still haven't touched UITK. Not too excited about dealing with style sheets and whatnot
Maybe it's because I'm not a web dev lol
You can just use C# if you're comfortable with that, really never use Ucss or whatever is called
Hey, I have a code that delete an object with Destroy when I click on it (and nothing else afterwards)
But when I run it I get this big error:
MissingReferenceException: The object of type 'UnityEngine.GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.Object+MarshalledUnityObject.TryThrowEditorNullExceptionObject (UnityEngine.Object unityObj, System.String parameterName) (at <adbae017f0374fce9921b97a33a4e8ca>:0)
UnityEngine.Bindings.ThrowHelper.ThrowNullReferenceException (System.Object obj) (at <adbae017f0374fce9921b97a33a4e8ca>:0)
UnityEngine.GameObject.get_transform () (at <adbae017f0374fce9921b97a33a4e8ca>:0)
UnityEngine.InputSystem.UI.InputSystemUIInputModule.ProcessPointerMovement (UnityEngine.InputSystem.UI.ExtendedPointerEventData eventData, UnityEngine.GameObject currentPointerTarget) (at ./Library/PackageCache/com.unity.inputsystem/InputSystem/Plugins/UI/InputSystemUIInputModule.cs:476)
UnityEngine.InputSystem.UI.InputSystemUIInputModule.ProcessPointerMovement (UnityEngine.InputSystem.UI.PointerModel& pointer, UnityEngine.InputSystem.UI.ExtendedPointerEventData eventData) (at ./Library/PackageCache/com.unity.inputsystem/InputSystem/Plugins/UI/InputSystemUIInputModule.cs:402)
UnityEngine.InputSystem.UI.InputSystemUIInputModule.ProcessPointer (UnityEngine.InputSystem.UI.PointerModel& state) (at ./Library/PackageCache/com.unity.inputsystem/InputSystem/Plugins/UI/InputSystemUIInputModule.cs:352)
UnityEngine.InputSystem.UI.InputSystemUIInputModule.Process () (at ./Library/PackageCache/com.unity.inputsystem/InputSystem/Plugins/UI/InputSystemUIInputModule.cs:2257)
UnityEngine.EventSystems.EventSystem.Update () (at ./Library/PackageCache/com.unity.ugui/Runtime/UGUI/EventSystem/EventSystem.cs:530)
Which apparently come from the input system, do I need to do anything specific to unregister my object or something?
Just seems like a lot of boilerplate code but I could be wrong
My brain just aligns better with IMGUI
is there a good guide on this? I also prefer a C#-based approach
there is some yes but you can easily create your own components
need to remember the exact link where it shows each equivalent styling for c# option
https://docs.unity3d.com/Manual/UIE-simple-ui-toolkit-workflow.html idk if this was the one its been a while since i touched the editor scripting
where it says Use C# script to add UI controls
Is it common to use UITK for ingame UI? Not editor
I dislike the gameobject based UI too so I'm considering that
they are pushing it but tbh ive yet to see it
the ability to live edit the style sheet and tweak the layout of a window is such a breath of fresh air if you're used to the cycle of changing margin sizes by a few pixels in IMGUI code and waiting for a recompile to see it haha
also last time i checked they dont suppot World Space canvas
I just think its neat for Editor especially its Event style approach. Also not having to type GUI.
every time you add visual element lol
I can definitely see the benefits of that yeah
Is it stable though? Any major issues?
it's totally possible to mix with as much C# stuff as you need i think, you can create some nodes and then load a separate stylesheet
afaik it's generally considered production ready for editor UI and not so much for anything else 😛
I see
until they have world space support we can't touch it for game stuff anyway
the stylesheet is useful if you dont want to write lots of c# boilerplate, but you can easily create your own Classes/components for visual elemnts
does UITK have things for more interactive stuff like detecting mouse movement and custom capture mouse events without having a control under the cursor?
One downside I see is harder portability to other engines, but who knows maybe I'll stick with Unity for the rest of my life 🤷♂️
isn't that already built in the Editor class somehwere
not sure! I need it outside the editor in this case
ohh right I think you mentioned this also being used in Runtime ?
yeah
the (currently in preview) AppUI package for UITK actually has a solution for world space canvas in it, it's pretty handy and also not that difficult to set it up yourself if you're so inclined
my use case is kinda wonky but I'm making a tool that's supposed to both run as a standalone .exe (a unity build) as well as in unity's scene view
which means I'm recreating a lot of the Handles.X stuff, and also, I want to share GUI between runtime and editor. currently I use IMGUI bc it's what I'm used to, and bc it has shared runtime and editor support, mostly
omg finally. I need to check that out
Show some code
I fixed it by moving it in a coroutine so now I have this
protected override void OnDeath()
{
CustomerManager.Instance.UnregisterCustomer(gameObject);
StartCoroutine(Delete());
}
private IEnumerator Delete()
{
yield return new WaitForEndOfFrame();
Destroy(gameObject);
}
Which is called by this:
protected abstract void OnDeath();
public void TryGiveBurger()
{
_health = Mathf.Clamp01(_health - GameManager.Instance.ConsumeCurrentBurger());
_healthContainer.localScale = new(_health, 1f, 1f);
if (_health <= 0f)
{
OnDeath();
}
}
Destroy already has a timer btw no need for Coroutine
Destroy(gameObject, myTime);
oh wait I see its WaitForEndof frame
Well the goal of that is just to wait one frame because if i do it directly it crash, so i just wait the smallest time i can
thanks! 🙏
My brain is not active right now. Can someone tell me why these two groups of code result in different rotations?
Oh shit it's Freya.
Hello, I am using this video as a basis for an npc tank in my game so it will move more like a vehicle
https://www.youtube.com/watch?v=mNoyPz3LCy0
But is there a way to impliment the navmesh with this movement so that it won't keep running into walls
✅ Get the Project files at https://unitycodemonkey.com/video.php?v=mNoyPz3LCy0
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
🌍 Interesting Game Dev Videos https://www.youtube.com/playlist?list=PLzDRvYVwl53vD6I_5QE8jV-TYjckA7w_w
Here's the Racing RTS I made for ...
this keeps being added to my permissions and I don’t know what is doing it? Is there a way to block it from being added
not a code question
where would I ask this then
use #🔎┃find-a-channel to find a relevant channel for your question
i noticed my character slightly sits above the ground (about 1 pixel) and i checked the colliders to make sure that they are lined up correctly and they are, but there is still a gap between my player and the ground
not really a code issue. but it is typically less noticeable if you have your objects sized reasonably. what you are seeing is the default contact offset, there is a setting for it in the physics2d settings but, again, it is less noticeable if you have your objects at reasonable sizes and don't have your camera view super small
Assets\StarterAssets\InputSystem\StarterAssets.cs(18,22): error CS0101: The namespace '<global namespace>' already contains a definition for 'StarterAssets'
im getting this error with the input system with the starter assets there is only one StarterAssets script idk why im getting this error
you have a duplicate script
i dont though
yes you do. Search for StarterAssets via your IDE
That doesn't mean there isn't another definition for StarterAssets, that just means you don't have another asset called StarterAssets
Hi Everyone
My issue happens when I try to build my project for for IOS.
The error comes in “ installing CocoaPods “ and requires an update to “Ruby”.
That’s where I hit the wall. Any Help please
not a code question. #📱┃mobile
those are the results within the StarterAssets folder. what about the rest of the Assets folder
for example, if you have perhaps created a type called StarterAssets then it would of course cause this issue
that was the entire solution
and when i delete the ones i have the refrences to it go to being a error
its fine if i dont generate a c# class
but i have
public void OnDebug(InputValue value) {
Debug.Log("Test");
}
on a object that has the player input component but it doesnt log the test
so you are deliberately generating a class called StarterAssets and are surprised there is a name collision with the StarterAssets namespace?
just change the name of the class you generate to literally anything that isn't already taken
that depends on how your PlayerInput component is set up
there's documentation pinned in #🖱️┃input-system to learn how to use it
is anyone able to help me out with this?
Most people wont really watch a video to help you. Yes you can use navmesh to calculate a path, then just grab the next position and simulate input towards that position for the AI.
Is it normal for you to feel intimidated by lines of code, but then when you actually code it yourself you're like "Hmm, not that bad"
you can have 50 lines and code be shitty and illegible or have 300+ lines but its legible and well organized, it should make the only importance
why does rotation only work after mesh is drawn(cont...)
chunk is created and instnatiated under parent transform, all its local position are set to zero
even if i were to set the rotation of its parent here, the rotation will not work
however, if i were to change the rotation AFTER the mesh has been drawn, only then does the rotation take effect.
Why is that?
Hello, I'm having an issue with setting the projection matrix of a camera. This is for an oblique view frustrum, which I don't fully understand, which is being used in seamless portals. I keep getting an error saying "screen position out of view frustrum" when I teleport or at seemingly random times
that usualkly happens when you set the ortho size to negative
this is using a perspective camera
might be thesame case, not sure
This is what i'm using to set the matrix, how would I test for the size and/or fix it
Vector4 clipPlaneWorldSpace = new Vector4(p.normal.x, p.normal.y, p.normal.z, p.distance);
Vector4 clipPlaneCameraSpace = Matrix4x4.Transpose(Matrix4x4.Inverse(refCamera.worldToCameraMatrix)) * clipPlaneWorldSpace;
var newMatrix = playerCamera.CalculateObliqueMatrix(clipPlaneCameraSpace);
camera.GetComponent<Camera>().projectionMatrix = newMatrix;```
If you set the parent to rotation (0, -90, 0) and generate it with the Rotation float set to zero (like you did at ~25sec in the video you posted in unity-talk), what is the local rotation of the child?
zero
all children main local tranform of zero
Sounds like you are generating the chunk in world coordinates then
Would need to see that code to help further
hmm, it most likely true
Yo so using some finnicky z-test stuff I've finally got some blackout stuff working just the way I want it to, but text does not properly show through walls. How do I make floating text appear above everything?
since you can't apply shaders to TMPro text elements they respect line of sight unlike the z-test ignoring elements
GameObject currSpawnPoint = Instantiate(spawnPoint, spawnParent.transform);
float x = boardRadius * Mathf.Cos(2 * Mathf.PI * i / numPlayers);
float y = boardRadius * Mathf.Sin(2 * Mathf.PI * i / numPlayers);
Vector3 pos = new Vector3(x, 0.5f, y);
currSpawnPoint.transform.position = pos;
player.Movement.Controller.Move(pos);
Vector3 relativePos = spawnParent.transform.position - player.transform.position;
Quaternion rotation = Quaternion.LookRotation(relativePos, Vector3.up);
SendSpawnLocation(pos, relativePos, player);
player.transform.rotation = rotation;
Debug.Log($"Player {i} moved to position: {player.transform.position}");```
when i try outputting the result of the x, y, z, I get a pentagon looking player distribution.
Hello I need someone who knows how to use Unity very well for realistic firearm models and realistic military equipment
where is the code question?
I don't understand can you repeat
where is the code question?
I use Google Translate because I am French, can you provide more details please
This is a server to ask code questions. What is the actual question
I'm looking for someone who could help with a game because I don't know how to do it but I have ideas
This server is not for finding team mates. You can use the !collab forums.
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
But word of warning, nobody wants to partner with an "idea" person. Good luck.
Hi, im trying to make my 3d first person charcter stop sticking to walls when in air and everywhere it says to use a 0 friction physics material but that just makes me go up the wall
That would be your code causing that then. If you want help with the code issues you should share your code
ill attach it in a second
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
are the walls slanted in any way?
no they are flat walls
I would use debug.drawray here so you can visualize what the vectors are, where it's trying to move.
But also I'd really try not to have many different areas that are adding force, or directly setting velocity. It becomes a pain to go through. Like now youd need to add a few debugs rather than just 1
This is a coding channel #🔎┃find-a-channel
shoot mb
When I added my source generator to package i noticed that it generates files seperatly for package and actual project that my package is part of... is it just a temp view and building will result in just one unique file to be generated? or is it this worse scenario where i have to redesign my idea around fact that code in my package will not have access to actuall generated based on Project it self ?
i have a object with script, where the script shows a value from a referenced ScriptableObject. It works fine in bothe editor and after build when I instantiate the object using "Instantiate". And when I instantiate that same object with "Addressables", it works fine in editor. But after build, the script doesn't show the updated value of the ScriptableObject. It shows only the value that was before the build. What is this odd problem?
The script to show the value:
using UnityEngine;
public class SO_Test : MonoBehaviour
{
public SO_Creator scriptableObject;
void Update()
{
Debug.Log(scriptableObject.x);
}
}
the script that instantiates and modify the scriptable object's value
sing UnityEngine;
using UnityEngine.AddressableAssets;
public class SO_Modifier : MonoBehaviour
{
public GameObject cube;
public AssetReference cubeRef;
public SO_Creator scriptableObject;
void Update()
{
if (Input.GetKeyDown(KeyCode.Q))
{
//Addressables.InstantiateAsync(cubeRef); ==> this instantiated object doesn't update the Scriptable Object Value
Instantiate(cube); // ==> this works fine
}
if (Input.GetKeyDown(KeyCode.Escape))
{
scriptableObject.x++; // Updating the value to test
}
}
}
its how SOs work. They just restore to their original value of build.
thats why you typically don't use them for save systems or anything
i understand now
then is there anything alternative
Feels like we're missing quite a bit of context to provide an answer.
looks good, thanks
Well point is: Source generator i created should just output one file. (creates static class with method to return certain marked types) and when i added to to my package i was suprised to see that it generates seperate files for each context (not sure if its per asdmf but for sure seperate for Proejct and package).
result i want: Source generator creats one file based on code in project it self so code in package can use this code generated based on what is present in project
I don't see how this presents a problem... code can still interact with other code even if its not in the same file
this one file have one unique static class... it does not generate diferent class based on context... it just adds elements to static array base on analysis
Where does it create the files? What does the generator code look like? What do the generated files look like?
using Ducknest.StatePersistence.SourceGenerator.Sample;
public static partial class MementoSerializationContext
{
global::System.Collections.Immutable.ImmutableArray.Create<global::System.Type>(new Type[]
{
typeof(Foo)
});
}
``` out put is likeso...
roslyn generator ( kinda assumed its obvious ),
w8 that one is buggy i just made small changes xD
but either way older version generets
It's not obvious, especially considering not everyone here has experience using source generation on daily basis.
And it's quite different from what I see in the docs example.
that doesn't look like any roslyn generator I've ever used
and I use it on a daily basis
using Ducknest.StatePersistence.SourceGenerator.Sample;
public static partial class MementoSerializationContext
{
public static global::System.Collections.Immutable.ImmutableArray<global::System.Type> MementoTypes = global::System.Collections.Immutable.ImmutableArray.Create<global::System.Type>(new Type[]
{
typeof(Foo) // GENERATED BASED ON CONTEXT
});
}```
its output ?
no, I thought you were talking about the actual generator itself
do we use here any specific side to share bigger pices of code than few liners ?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
a powerful website for storing and sharing text and code snippets. completely free and open source.
generator it self is work in progress either way... point being: when I inspect MementoSerializationContext placed in some script in Project it points to different file than inspecting one placed in my package... so from my package i can't access to Types Marked in project code... all i want is to avoid reflection and boxing.
😮💨
So, do I understand it correctly: you want your package to have access to the types in the project?
yeep but thats not the issue i am concern right now... its just that source generator is executed seperatly for Project and package and i dont know of way how to controll it in unity :/. in docs i saw only tutorial how to setup generator .dll
if i could force it to run only on project side and even toss in there generated asmdf than it would solve that one problem either way :/
I think you'd need to check the assembly name in the compilation provider. If it's your package assembly, then don't generate anything.
Honestly, this is quite a bit outside the scope of unity help. Might get a better reply in the C# server.
its unity package thou :S. its not detached project.cs /solution .sln its in my com.ducknest.---...
could someone help look at my unity build profiler with me to figure out why its so laggy despite it running seamlessly within the editor?
post it. dont ask to ask.
Then I'm not sure what you mean by a package. Is it supposed to be a package that you install via package manager?
well i was hoping someone could hop in a call
this is my profiler
Are you setting target frame rate perhaps?
are you using 3rd party scripts that might be doing that?
no i followed a tutorial and the game runs fine in the editor and then runs bad after a few seconds in final build
it means locking the render / frame rate
Ok, so it is a package. Meaning it's a separate assembly.
how can i check
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
which script i have multiple in the project
The asmdef in your package also makes sure it's a separate assembly.
well... when did the issue start?
when i built the game
at the end of development
its a super simple flappy bird clone too
did you try restarting the editor
its a separate build, nothing to do with the editor but ill try exiting all of it
oh I misread what you said. I thought you said it was happening only in the editor
no only in the buildf
Try searching for Application.targetFrameRate in your ide.
in the unity editor?
i never wrote that in any of the scripts so what do you mean?
In your code editor(ide), like Visual Studio. Do a global search(ctrl + shift + F)
not there
turn vsync off perhaps
vsync off in the build settings?
sure
i dont see that as an option
quality settings
and where is that?
you can just open project settings and type vsync into search field
can you hop in a call with me?
no
okay where is project settings
edit -> project settings
With all these questions you should really go over the basics of using unit: !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
well it showed up. so its somewhere in there
im trying to fix one specific issue so pointing me to a thread with 750 hours of content will not necessarily help me rn
vsync count is set to every v blank
set to none
It would help you understand how to use unity though. Such that you can find the quality settings for example.
okay i set it to dont sync
idk why vsync would be locking it to 15 fps, that's strange. but its worth a shot
that fixed the issue
lol
so we don't know what that means?
no lol
144
turning vsync off also helped me in other games in the past
like playing them i mean
I mean vsync works fine for me especially with gsync
I play with it on in everything
Might be something wrong with your hardware or OS/drivers or their settings.
so having vsync off in the project build settings is good or bad when relasing the game to the public?
wouldn't that make it slower for most people?
so for every game i make i need to account for that just because my computer is weird
disabling vsync would cause screen tearing. So you usually want it on.
yeah but im confused
if you have a gsync monitor you also need vsync on for it to work properly
I would test that next if you really want to figure it out
either way it shouldnt affect my unity game
i think it wont affect other users
just me
because i have vsync on
🤷♂️
maybe i should check my vsync drivers if thats a thing
Yes, it probably wouldn't affect other users. Might want to test your game with vsync on on a different pc.
still, thank you @void basalt
@void basalt i hooked up a display port and turned vsync back on, still was laggy
i have an amd graphics card with freesync turned on so irdk
im really confused now cause i switched back to hdmi and it runs smoothly now with vsync turned on
Any ideas how i would clone a object and store it in an array
clonedObjects.Add(clone);```
Using c# ? And what if there objects with the same name
unity only uses c#
idk what u mean abt them having the same name
theres no problem
boof monitor
is my only guess
Sorry if you are reading this, didn't mean to reply
So I'm working with an InputField, and I have pretty much everything working right with it except that when I use multi line submit as my line type. Whenever I hit submit (in this case "enter") I get a new line at the end up my input, messing up my whole thing I've got goin. Any suggestions?
nvm solved it. I've come full circle. I can't seem to prevent a new line when I submit.
Pretty much my exact issue with TMP 3.0.9
https://discussions.unity.com/t/tmp_inputfield-adding-new-line-after-submit-when-line-type-is-set-to-multi-line-submit/839541
Hello, I'm trying to create a simple debug function to categorize my debug logs and enable/disable them by categories. So it works exactly like Debug.Log with an added "category" parameter. My issue is that Debug.Log allows any type of variables while for a new function, I can't pass a generic obejct
I tried using the type Object as the first parameter type but then using it with a string triggers the errors that a string is not an object type...
Any ideas ?
OK, found my answer:
public static void DebugLog<T>(T obj, DebugCategory category)
So, for a rigidbody-based movement controller, is it possible to have player-input rigidbody forces be limited by a speed cap, but have outside rigidbody forces be not limited?
Hey I need help about a thing : I'm making a game where you can pickup objects but the object position (which is being set relative to the mainCamera position) is being updated less frequently than the camera's position so it is late and stuttering. Any help?
I linked a video in the reddit post
ok idk why the video is no longer in the reddit post
you should show the exact errors/line with the error. I dont really see why you would need a generic here that isnt constrained to anything. every object in c# has .ToString()
Just having public static void DebugLog(Object obj, DebugCategory category) should be fine.
the rigidbody doesnt store where forces came from, you'll have to keep track of that yourself.
im sending a link to the video
Post the !code as text 👇
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
look at the #854851968446365696 on what to include when asking. you dont need to show a video. if you say it's stuttering then showing us a video of it stuttering isnt really gonna give us new information.
alr so should i send the code instead?
Okay, how do I do that?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
using UnityEngine;
public abstract class Pickupable : MonoBehaviour
{
public float xOffset;
public float yOffset;
public float zOffset;
public bool isPickedUp;
public GameObject playerCamera;
public float throwForce;
public float rotationTorque; // Rotational force for throwing
private Rigidbody rb;
private Collider collider;
private PlayerInteract playerInteract;
void Start()
{
playerCamera = Camera.main.gameObject;
rb = gameObject.GetComponent<Rigidbody>();
collider = gameObject.GetComponent<Collider>();
playerInteract = playerCamera.GetComponent<PlayerInteract>();
}
void Update()
{
if (isPickedUp)
{
// Move the object relative to the camera's orientation
Vector3 offsetPosition = playerCamera.transform.position
+ playerCamera.transform.right * xOffset // Apply xOffset relative to camera's right direction
+ playerCamera.transform.up * yOffset // Apply yOffset relative to camera's up direction
+ playerCamera.transform.forward * zOffset; // Apply zOffset relative to camera's forward direction
gameObject.transform.position = offsetPosition;
gameObject.transform.rotation = playerCamera.transform.rotation;
if (Input.GetKeyDown(KeyCode.Space))
{
Throw();
}
}
}
public virtual void PickUp()
{
isPickedUp = true;
playerInteract.pickedUpItem = gameObject;
if (rb != null)
{
rb.isKinematic = true; // Disable physics while holding the object
}
collider.enabled = false; // Disable collision
}
public virtual void Throw()
{
isPickedUp = false;
playerInteract.pickedUpItem = null;
collider.enabled = true;
if (rb != null)
{
rb.isKinematic = false; // Enable physics when throwing
// Apply force to throw the object
Vector3 throwDirection = playerCamera.transform.forward;
rb.AddForce(throwDirection * throwForce, ForceMode.VelocityChange);
// Apply torque for rotation
Vector3 randomTorque = new Vector3(
Random.Range(-rotationTorque, rotationTorque),
Random.Range(-rotationTorque, rotationTorque),
Random.Range(-rotationTorque, rotationTorque)
);
rb.AddTorque(randomTorque, ForceMode.VelocityChange);
}
}
}
Post it using the large code blocks guide (via the links provided)
ok
im using a character controller to move the player
if u need the movement code i can provide it
you store it yourself in the type Vector3. a lot of this really depends how you want this to work in your world and what you consider an outside force to be. Like if free moving rigidbodies in the world should push other objects, then one way ive seen someone else say is using this method https://docs.unity3d.com/ScriptReference/Rigidbody.GetAccumulatedForce.html.
If you dont want rigidbodies to push each other, meaning you want to control that all yourself, then it'd be simpler to have a function for like knockback in your custom script.
Move the object in LateUpdate instead. Or just make it a child of the camera while holding it, then you don't need to move it manually at all
I'll look into this. Thanks.
the problem with making it a child is that when im making it a child inside the code it changes its shape everytime i pick it up because my player scale isnt 1 1 1
ill try late update
Basically, the method I'm hoping for is this.
Any force that is applied to the character by the player's own inputs - Input Force
Any other rigidbody that interacts with the player - Outside Force```
Sry, it's hard to describe
Basically, what we're trying to do is add force to a rigidbody such that it accelerates until it reaches a certain speed. Say their X speed reaches 5.8 while the max allowed player speed is 6, but their acceleration adds 1 per step. At 5.8, it'd only add 0.2 to their speed and not add any more force in that direction as long as the X speed is greater than 6
What I said above would still apply, though you need to consider what an interaction is. Like in my game I use rb movement, but characters dont actually push each other via collision. I do knockback only, meaning I can just call a method on the other rb.
If you truly want it for any collision then look into that method I linked. I havent used it myself but seen another suggest it for this use case.
Thank you so much late update worked! Mind if I ask why is this so?
I think our biggest hurdle is the player's horizontal movements being negated while airborne.
Like, say a diagonal launcher that would normally fling a physics object away in a diagonal arc. It keeps going in the direction it was sent until it lands.
But the player, it gets launched for a bit and its horizontal speed is negated because the player input axes are zero, and it just flies purely vertically.
It makes sure that the camera has already moved that frame. So move camera -> move object instead of move object -> move camera
oh ok
smart
You're reinventing the wheel
.NET has an ILogger<T> class, where T is the context, or category
I'd implement this interface and have it log debug messages
Then create a static logger factory and get an instance of the ILogger from there
Also, regarding your issue; I believe you can use a string for the categroy instead with ILogger, but I am not sure
Either way, it's not possible to do this unless you create a dummy class
How can I destroy a gameObject from inside regular C# class?
Nvm I found it.
Object.Destroy();
Is there a way to stop coroutine from regular C# class or do I just pass an Action callback for that?
you should pass an action callback
coroutine-related functions are from unity's monobehaviour because they rely on the update loop
Expose a method on your MonoBehaviour to stop it, and call that method
Thanks, I will either pass Action or do it from monobehavior side
You may want to google ZLogger, Serilog, NLog and log4net.
I dont see the problem in the solution they already figured out
No, it didn't work with Object directly. I already found my answer as I replied earlier:
public static void DebugLog<T>(T obj, DebugCategory category)
Using <T> allowed me to pass any type to my function which I then pass to debug.log directly if the category is enabled.
This is confusing, <T> wouldn't be the category if I understand correctly, it's just the variable to debug. The category would be an additional parameter. I already found my answer with
public static void DebugLog<T>(T obj, DebugCategory category)
I didn't know about those but I just wanted a really simple method here. I found my solution and I can enabled/disabled my categories easily through on external XML config file which doesn't need to be recompiled like it would if the config was hard coded in the scripts. Full function:
public static void DebugLog<T>(T obj, DebugCategory category) { if (Config.Data.Bool("/c/debug/" + category.ToString().ToLower())) Debug.Log(obj); }
I'm using an enum for categories so I can remember what categories I have and those enum are also used in my config file to control which one I want to enable. I guess the classes mentioned before do the same but considering the simple thing I wanted to add, it's just as easy to add a basic method like this.
Yeah, no need to pollute your codebase/project with external stuff when you can do something as simple as that.
"Didnt work" is very vague. I dont see anything in that function you showed that requires generics
That's also true. I don't see why the generics, object would be enough
Why would you need a generic for the variable to debug? The only reason why you'd need a variable is for the string representation, in which case you pass it as one of the arguments
And before you wonder, you can avoid boxing. It's a bit of an extra process but if you implement that it's actually the most performant possible way to log.
The whole point of the generic is to represent the category, and if you were to pass the variables with them then you'd have to make plenty of overloads for all the different variables a single logger message might have
Also, @cold parrot mentioned Serilog and this is actually a very common way to log. You can also try using that. You can make a sing very easily (there are existing repos that did this) and it is very scalable with future additions. It's a very good way to properly log in your application
BTW there is confusion here. The generic is given on the class level, not method level
You can still pass generics for the parameters if you want to log the whole object. You specify the category on class level in the factory using the generic
Also, why would you want to pass a category in every single method? Why make it an enum? A category is usually categorised based on the class that calls it, so it makes no sense to use an enum. Right now you just repeat yourself by having to pass a category with every enum, even though the logger should already be aware of it
I kinda have a feeling its AI code. I'm not really sure how someone would end up at this after seeing a cannot convert object to string error.
Especially since their paraphrasing of the error was "string is not an object type"
Also, another very important thing; the standard ILogger builder has the ability to pass configuration to disable categories, or change their logging severity. That's gonna save you a lot of reading
It also has support for something called ConfigSnapshot or whatever and you can edit your app settings and immediately delegate that change into the loggers
All of this also applies to Serilog, btw
Does anyone know some good resources for getting started on combat systems? I'm not really sure where to start
"combat systems" is very vague
start by breaking down the problem into smaller easier to solve ones
hi, I'm trying to code a movement controller for a 2d platformer right now. I am slowing down the player when on the ground using Rigidbody.drag, and in the air I set that drag to 0 so the player falls faster and can preserve momentum. The problem is that now the player is faster when in the air, how can I compensate for that?
at least for what im trying to make, I need a way to swap out a weapon, a way to register damage, a modular way of making weapons, the one thing I'm not sure how to figure out is how to change how you attack based on the weapon. Like how to change the logic of attacking with a melee vs a bow and arrow for example.
Still incredibly vague. We don't even know what kind of game this is. A JRPG? An action game like Horizon New Dawn? A strategy RPG?
its an fps game with both ranged and melee think similar to smth like shady knight
tbh for this can be as simple as enum, or some type of distinguishing between weapon types etc.
Maybe even scriptable objects. Sounds like you might be jumping too much ahead though, I would start building the basic system first then, practice, trial n error different ways
if its an enum would i make it so in an attack function i would do if == melee (this logic) else if == ranged (this logic) ?
not the attack logic itself , you could have a special class that does the specific thing
you don't even have to check for attack types, mainly for animation poses or whatever needs to be according to weapon type, say a melee or two handed weapon like bow
Enums not the most flexible to add more later on, but if you plot it well you don't need to. Then it could be as simple as an event
OnWeaponChanged(WeaponType weapontype)
if(weapontype == WeaponType.Melee)
//Hold a melee pose
you wouldn't use it for attacks though as your weapon current is already what you need logic wise
you just need common methods, like abstract classes can override method etc
if they all have say a Attack() or Use() method, doesn't matter which one you hold because they all will run that same method but in different ways
oooh okay I think I get what that would look like, do you mind if i screenshot that so i can look at it later on?
yeah sure lol
aite ty :^)
the real choice would be, do you go with Inheritance or Composition, or maybe both
ive actually never heard of composition ive used inheritance b4
Inheritance
Sword : Melee : Weapon
or Composition (also making specific components)
IWeapon or IMelee
etc
would u say the composition approach is useful?
oh wait
is composition just interfaces?
not necessarily no
afaik more or less it just means building an object without inheritance
but they(interfaces) do help decouple and create things by composing them together
So IWeapon can have Weapon functions but it can be something else besides a traditional weapon class, if that makes sense
so basically you can have an object share common methods/properties with other classes without them both being from the same Parent class / tree
hey there
ill go straight to the point
i have problems with the animator
anyone mind helping me out?
you can start by not pressing enter every line
I know what youre saying, but its mixed with the code
but sure ill try this one
ooh okay, so its basically having having the weapon functions but you can build your own functionality in them without them needing to inherit from that base parent class
Either way you need to explain your problem if you want help
I know
yeah Like i Want this Stick to have Weapon methods like Throw and Hit or whatever, but still be a IPickupable so I can scoop it up in my inventory etc.
Not the best example but I still haven't taken my morning brew 🍵 hehe
LOL funnily enough that was the example that made the most sense to me
thanks for your help ill try it out :^)
np. Goodluck in your journey 🙂
Hello, ive got an issue with my inventory system where if i have more than 1 item in it, and i try and drop the one im holding all the other items in itemList are replaced with empty objects.
remove item method - https://gdl.space/odoyinited.pl
whole script (just incase) - https://gdl.space/mugekucepi.cs
bump
put the drag back how it was, and maybe if you want to fall faster just multiply the Physics.gravity value * multiplier for player, so you have an AddForce downwards
but my drag on the ground is set to a value that makes the player stop immediately, i don't want that in the air
maybe make it lower but not completely 0. How else do you want to compensate
not sure tbh, that's why i asked here... i thought maybe i could calculate a multiplier i can add to the speed based on the drag in order to make them the same or something like that
you could probably do that sure, or just make airMoveSpeed variable to compensate the difference in drag
that's what i thought too, is there a formula i can use to calculate that value or should i just eyeball it?
Probably, I personally don't know a specific one but I'm sure you can come up with something fairly easy by trail and error
alright, thanks!
bump
does anyone know how to fix this error message: "NullReferenceException: Object reference not set to an instance of an object
PlayerHealth.UpdateHealthUI () (at Assets/PlayerHealth.cs:34)"
here is the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerHealth : MonoBehaviour
{
private float health;
private float lerpTimer;
public float maxHealth;
public float chipSpeed = 2f;
public Image frontHealthBar;
public Image backHealthBar;
// Start is called before the first frame update
void Start()
{
health = maxHealth;
}
// Update is called once per frame
void Update()
{
health = Mathf.Clamp(health, 0, maxHealth);
if (Input.GetKeyDown(KeyCode.A))
{
UpdateHealthUI();
TakeDamage(Random.Range(1,10));
}
}
public void UpdateHealthUI()
{
float fillF = frontHealthBar.fillAmount;
float fillB= backHealthBar.fillAmount;
float hFraction = health/maxHealth;
if(fillB > hFraction)
{
frontHealthBar.fillAmount = hFraction;
lerpTimer += Time.deltaTime;
float percentComplete = lerpTimer / chipSpeed;
backHealthBar.fillAmount = Mathf.Lerp(fillB, hFraction, percentComplete);
}
}
public void TakeDamage(float damage)
{
health -= damage;
lerpTimer = 0f;
}
}
you know how to post code properly here, do so
frontHealthBar is null / not assigned value
also this should be in #💻┃code-beginner
oh whoops im sorry, i miss clicked i thought I was in beginner
Hello All,
I have a hierarchical state machine. Each state contains its own state machine that allows it to have a child state. I would like to create a recursive function that goes down each node in the current branch and checks if the input state is an option. Here is an example of what I would like to achieve:
TryChangeState(State someState){
//Check if the current state has the option for someState as a child state
//If it does
childState is set to someState
//If it doesn't
childState.TryChangeState(someState)
}
The way I currently have it setup, is each behavior state is a class derived from one overall State class. The derived states have a reference to all the states that could be their child states. For example:
public class Battle : PlayerState
{
public OperateCannon OperateCannon;
public BattleFreeMove BattleFreeMove;
//some functionality
}
How can I check if a derived class has a reference to someState? I imagine generics may be involved, but I haven't found a good resource to learn this yet. Here is some more specific sudo-code of what I'm looking to check:
if (derivedState contains a reference for someOtherDerivedState){
//DoSomething
}
Any suggestions on how I would achieve that?
^I'm thinking each state may need to have a List<States> for all available sub-states.
I need some help
!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
how can i find what Vector3 is about 85% of the way between 2 different Vector3's?
Lerp
the dot product
it gives you a value between -1 and 1 representing the angle between the 2 vectors
-1 means they are opposite
1 means they are in the same direction
be careful to normalize them before
@gloomy osprey
I understood that they need a vector 85% between two points, where Lerp is the correct tool
hello,
i have been having an error at the Guns[gun] i tried Guns[gun.position] but still didnt work any ideas (i wanna keep this way its simpler for me to understand)
You don't need Guns[index], you already have gun.
wait i just realised that
Replace Guns[gun] with gun
You'll need to use the position property as well
You should have the foreach loop inside the if-statement and not the other way around.
but the thing is i have three transform from where the bullet initiates
only the top one works
the other 2 dont
how me fix ?
Did you move the if statement outside like Dalphat suggested? That should fix it.
no lemme try that
Otherwise after the first iteration, you have changed readyForNextShot and in the next iteration you can't shoot
it worked 
if (...)
{
foreach(...)
{
...
var instance = Instantiate(prefab, ...);
instance.transform.right = direction;
Destroy(...);
}
}```
With a custom inspector it is not possible to change how something is displayed in debug mode right?
I have a simple custom inspector that adds a label for a certain value to the inspector so i can view it easily when testing.
Everything is working as intended but im still getting this error?
wait im a numpty
It's the usual warning when you try to pass the wrong type to a method. If you use "Object", you need to pass an Object. The string is technically an object but you'd need to cast it to object for the method to accept it. I forgot the exact message though.
I don't know what boxing is and I'm not sure how I see this can be more efficient. It's a simple function which calls Debug.Log with a category used in a IF. How could it be more efficient?
Yes, I want to avoid 100s of overloads, using <T>(T...) allowed me to avoid exactly that. Using (Object ...) does not work.
Hm, from the name, it could be more interesting than Debug.Log if it actually serialize the object fields and properties automatically during a debug, I'll lookt into it. Thanks!
{
GameObject spawnParent = GameObject.Find("SpawnPoint");
GameObject currSpawnPoint = Instantiate(spawnPoint, spawnParent.transform);
float x = boardRadius * Mathf.Cos(2 * Mathf.PI * i / numPlayers);
float y = boardRadius * Mathf.Sin(2 * Mathf.PI * i / numPlayers);
Vector3 pos = new Vector3(x, 0.5f, y);
currSpawnPoint.transform.position = pos;
player.transform.position = pos;
Vector3 relativePos = spawnParent.transform.position - player.transform.position;
Quaternion rotation = Quaternion.LookRotation(relativePos, Vector3.up);
SendSpawnLocation(pos, relativePos, player);
player.transform.rotation = rotation;
Debug.Log($"Player {i} moved to position: {player.transform.position}");
if (Physics.Raycast(player.transform.position, player.transform.forward, out RaycastHit hitinfo, 200f))
{
Debug.DrawRay(player.transform.position, player.transform.TransformDirection(Vector3.forward) * hitinfo.distance, Color.red, 1000);
} else
{
Debug.Log("Nun");
}
arranged = true;
}
why are the player's and spawnpoints world positions different?
only one of the players goes to the correct position
🤦♂️ it works but if you refuse to show the actual error and code you had at the time, then not much can be said. You do not need generics here.
Here prove it to yourself https://docs.unity3d.com/ScriptReference/Debug.Log.html. Take a careful look at what parameters Debug.Log already takes.
im not entirely sure what im supposed to be looking at with those screenshots. If you're comparing the position from the debug.log and the inspector, then that wont align. The position you see in inspector is a local position while you're printing out the world position
I tried again and you're right. My issue was that I was using the keyword "Object" instead of the keyword "object", first one seems to be considered a class while the second one a generic type indeed. Using "object" works fine indeed. Completely forgot about this distinction, even though the color code of Unity is quite clear about this difference. Didn't pay enough attention. Thanks for your time!
replying pretty late so it's alright if your offline now, but when i did the Lerp between the start and end with 85% (0.85) it set the new Lerped Vector3 directly on the start point
player.transform.position = Vector3.Lerp(player.transform.position, Trailer.transform.position, 0.85F);
the result was equal to Trailer.transform.position
The result should have been 85% of the way from player position to trailer position. If you're calling lerp indefinitely, it'll look like it's reached the trailer position in a split second but it would technically never be there. It would always be 85% from it's current position (a changing value if called more than once) to the trailer's position.
no the lerp is only called once, and ive tried it at 15% and 85% and i get the same result
You've probably got something else going on. It should definitely not give you identical results.
ill make it do it again rq ive changed the code a bit since
ill send the code in a sec
line 33
is the IEnumerator its ran in
Try logging the position before and after lerp.
The result you see from the inspector may be due to something else
alr
ah its cause the lerp is being ran like its in an Update()
Hi, friends, I've set TimeScale=0, and now when I try to update an object's transform, it isn't being reflected in the running game's scene. Does anybody know why this might be happening? I've used log statements to verify that the code is being run, and the transform's dimensions are being updated
Because time isn't flowing? How are you moving your object?
when does On Validate actually occur?
I have my field set to my scriptable object in the inspector... but every time I first open my project my on validate function always throws these errors but only the first time i load up the project, it doesn't do it after that:
if(_blueprint == null)
Debug.LogError("Blueprint must not be null for Object " + _blueprint, this);```
Why is that? its super annoying as my console gets filled with false errors
how does one make a video player from scratch using ui?
Hi I am using this behaviour tree for the first time
how do i control my animations directly from this
without using the animation controller ?
for more direct control
How much from scratch? Like the video format and decoder as well?
Maybe with playables API.
hello again, i wanted to add recoild to player i get the recoild in the y value but it never works with the x value
even tried rb.addForce
Why are you using the y co-ordinate twice
any ideas for the question ?
Usually the reason is because the movement code overrides the recoil
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
right, the movement sets the x velocity directly which overrides whatever the recoil code does
so any ideas how to fix it ?
Start using AddForce instead of setting the velocity directly
same thing happening
Everywhere, not just there
wai lemme try something
what do you mean ?
Your movement code overrides all other forces. You have to change the movement code.
in which sense then how will move my player
with AddForce
Something like that, except you have to multiply by Vector2.Right as well
rb.AddForce(Vector2.right * horizontalInput * Speed, ForceMode2D.Force); like this ?
it works now everything is slippery
You'll have to tweak things like drag and friction
should i do something like this ??
I would start with drag and friction but you'll have to experiment what works best
like materials ?
private void Drag()
{
if (grounded)
rb.drag = GroundDrag;
else
rb.drag = 0;
}
``` ?
Friction is in materials, drag is in rigidbody
My unity is glitching out
I have a normal working code and for some reason whenever i launch my game, it says that "light is somehow not assigned"
UnassignedReferenceException: The variable Light of openDoor has not been assigned.
You probably need to assign the Light variable of the openDoor script in the inspector.
openDoor.Update () (at Assets/openDoor.cs:19)
You probably have multiple instances of the script in the scene
I just wanna use it for multiple doors
the cube on the right for example
is supposed to open and close
if the door is closed the lights go off
Well every instance will need that variable assigned
Search the scene for the script and make sure they all have it
every button and door has the script propely connected
with the items and objects assigned
if(Light == null)
{
Debug.Log(name + " doesn't have Light assigned", this);
}
Put this in Start
you really helped out thanks
Hi, i want to organize my code for projectiles better. I have an abstract projectile class with methods for moving, homing, bouncing etc. There are also abstract methods for collision with enemy units, walls, other projectiles and so on. Problem is most projectiles are simple and only need a couple of them, so i'm left with a lot of unused varaibles in the editor. I'd like to have something like multiple inheritance, for example a child projectile inhering homing projectile and bouncing projectile classes.
You can use interfaces for multiple inheritance. You should draw a diagram to clear your mind, just define the features and variables that all projectiles need, like speed, direction, tag/layer that can be hit, ammos, etc... In your case I think homing, bouncing are rarely used, so I would separate them to other abstract classes (or normal classes) like KinematicProjectile, HomingProjectile and BouncingProjectile, which would inherit from the base class.
You can use interfaces for multiple inheritance.
do not bastardize interfaces to be a substition for multiple inheritance. interfaces are not inheritance and should not be used that way
you should use composition rather than inheritance for this. have one "Projectile" component, and multiple components that the main projectile component uses to determine its behavior on the specific actions you want it to.
ah yes exactly I agree with that. I mean can be use multiple interfaces, can't inherit from multiple classes
Why must I manually GetComponent<>() in the Start()? Isn't C# capable of looking at components that I declare as variables through reflection, and then assigning them implicity?
probably performance implications
https://gdl.space/ubecimiyer.cs <= Enemy Ai
Can someone tell whats wrong here i cant point out the problem
doubt, its a one time thing right
not every frame
not always
btw SerializeField exists, you tehcnically can go without needing GetComponent (assuming you don't want a component at runtime like a raycast)
I dont want to manually drag mouse into stuff
I already use [RequireComponent
why not ? its good to have everything locked in
the RequireComponent does that
all it does it add a component
having it as serialized actually makes it too flexible. Now I can put random stuff in the field
it doest GetComponent for you
well not really, you can put specific types
SerializeField will not automatically getcoponent
unless I first go back to the editor, then manually drag something into the slot
which is more effort than just typing GetComponent
it doesn't but less time wasted fetching component when its already there
GetComponent has its own cost
but if I made it serializeable, that makes it possible to assign it to a different component
like, the same component on a totally different entity
it opens up the door to nonsensical flexibility
so what happens if you have TWO of the same type on the same object?
you can put two components of the same type on a single object?
no limit to how many of the same type can go on gameobject, yes
hm when would I do that
like i would never put 2 character controlelrs on a game object
no but you might have 2 audiosources or 2 or 3 weapon, 2 colliders, 2 renderers etc. etc... it does happen
you can't be specific with GetComponent but Serializing can
also unless you're clever about using OnValidate to getcomponent before run, you have a slight bigger load time because now all the objects are doing GetComponent
any ideas ?
did you send the update version of the script?
line 48 is landing on { so make sure you sent the updated script
Are singletons for something like the player object worth it in a singleplayer game or should I stay away from it.
if you can stay away, you should. But not from singletons as such, but from global variables and globally modified state.
If I want like a SoundHandler wouldn't that be good? What else would I do?
the lines still doesn't match lol
Call methods on an interface or some other form of indirection that doesn’t makes it impossible(difficult) to ever change how that audio handler works
lol
What should I do then
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Learn about game dev patterns, understand when to apply them, and when not to. Start here: https://gameprogrammingpatterns.com/ (it doesn’t matter that the code on that site is in c++, it’s about patterns, not copy & paste)
im a newbie
The message is not coming from this script
click on the error message and it would show you
this is the script
i dont know whats wrong because when i go and try and pick up something its supposed to be stored in my inventory
but it deosnt get added
Did ChatGPT write this script?
erm it had an error before but then i used chatgpt to change it and before i added inventory it worked
so yes
and how can u tell ?
was that a guess or
the comments on the first one gives it away i wont lie
plus some of the code is questionable
yeah i agree on that one
If you had wrote that message in the script you'd know where it is
yea... i have no idea
i was just forced into doing a project which i dont want to do 😭
We can't help with GPT-generated code
i understand
thank u though
do u know what i should do next since it cant be helped?
reset it and write it yourself
wtf chatGPT-generated code used GameObject.Find like that? Omg that's horrible code
you should learn how to debug your code and you will understand why so many errors are showing up
sadly i dont have much time to learn as this is due in like 2 weeks
and how much time do you think you will waste if you don't learn?
If you don't want to learn how to code, then you're in the wrong place 🙂 If you're looking for somoene to solve the problem for you, you want a contractor. I would start on fiverr.com
But it sounds like either you're a student in the wrong college class, or you have a job with a boss who has unrealistic expecations of your skillset. In either case, the unity discord isn't a place to hand off a problem to someone to fix for you.
We're more of a "teach you how to fish" forum
i understand
so don't you think it's a false economy not to learn, do yourself a favour, learn
you can !learn to debug in 2 weeks
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
you can learn to debug in 2 hours
true
Just looking at your code, I think you have an earlier error in your console. Looking at the last error is usually not a good idea. Look at the FIRST error in your console to see what happened that caused everything else to fail
Hello, so I was trying to make a script to move my camera smoothly to a set target, and I ended up with this code via a youtube tutorial. The problem is when the camera is done moving, it teleports to looking at the initial point. Any ideas why this happening? Thanks!
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Slerp is current = start, end, t. you are doing current = current, end, t
ooh I see
lemme change that
thanks!
I'm sorry but it is still happening...
https://gdl.space/abiwimozab.cs, I added the start transform variable in the IEnumerator
The problem is somewhere else. Probably some other code rotates the camera and this only overrides it temporarily. Find all the code for camera rotation
So I'm generating polygon meshes based off a radius. Should I generate the polygons with a radius of 1f and scale it via transform or just generate the mesh based off the radius? Or is there no difference at all?
Ok, thanks, Imma check some scripts
Found it, tanks!
Super open ended--and I ended up trashing my code I had the other day cause it was too buggy.
Anyone have ideas for how to make a wave based generator like PVZ? Where there's always sort of a trickle of enemies that get more frequent over the level. It getting more frequent is pretty easy to get working, but I'm having trouble with doing this ALONG with storing what enemies I want to spawn, at what point they should spawn in the level, the weight of their chance to spawn, it's a lot. I also want to keep it very modular in one script with serialized fields that I can drop into a new level and change around the stats.
I tried to make it work by having multiple lists, one of the enemies, one of the number of enemies, one of their weights, one of their score requirement, one of the spawntimes for score, it was all a lot and the lists really bug out
Really i want to find a good way to organize this all
I would love if I had a way to just do
Wave 1:
Enemy type: Bad guy
Amount: 3
Weight: .4
Enemy Type: Bad guy 2
Amount: 20
Weight: .6
You can do it that way ?
I guess I could instantiate a wave script to hold the wave data and keep multiple inside a list?
class Spawn
Wave[]
class Wave
Enemy[]
class Enemy
type
amount
weight
It worked on paper but it was a lot to manage, plus the lists don't play very nice (Like when I had 0 of something left then suddenly the script would read it as Null instead of 0)
I mean, it is as simple as @knotty sun wrote.
You can then have your spawn script iterate all wave and spawn them accordingly.
Does anybody know the encryption method for .dat save files for mobile unity games?
Dont crosspost #📖┃code-of-conduct
Okay
hello, im having an issue with my inventory script where if i have more than 1 item in it and i drop one the next available item is switched to as its supposed to, but the visual spinner isnt updated and i tried just spinning it but im not sure how to get it to go in the direction that will put another item in the correct visual slot
remove item method - https://gdl.space/ihabocakiv.cs
Looks like you're able to rotate between inventory items. What's the issue?
i mean like, when i drop an item and ive got more than 1 in the inventory - the spinner doesnt move to the correct slot
I'm not sure what you're referring to by visual spinner
What happens instead?
all the items in the inventory UI stay there and there is just nothing in the selected slot VISUALLY, but there actually is because its picking up my scriptable object data and replacing the item name and description in UI with its data
if that makes any sense
Maybe when you're about to drop an item, reference it first then spin. Finally drop the previously referenced item.
nono, all the dropping stuff is fine i think i explained it badly lol. the issue is the UI not updating correctly
the cubes on the spinning inventory wheel in the video arent updated
Right. The code simply sets the next item active and doesn't do any spinning.
yes
So spin it - we haven't seen your spinning implementation yet.
yeah i had that in for a bit, but i couldnt figure out how to get it to spin in the correct direction so that the newly equipped item was shown in the right slow
slot
Show your spin implementation
give me a min i need to put it back in
How are you spinning outside of item removal?
arrow key presses and im just rotating it by 90f and also incrementing heldItemIndex
Alright. Well, there isn't enough information and I've got to go.
okay lol
here it is with spinning implementation for anyone else - https://gdl.space/ihabocakiv.cs
but that only spins it one way im not sure how to find which way to spin it depending on where the next item is
What am I not seeing? Whenever I press spacebar the gameobject is instantiated but it throws a null reference exception for line 14
Got a question. Let's say I split up my player script into multiple scripts, so I have separate scripts for movement, head bob, etc. How can I tell the head bob script to start the jump bob coroutine from the movement script?
Use GetComponent and call a function on it
I probably wouldn't split them up that way, though.. Or at least if you have a parent orchestrator, it talks to all the various animator components directly
So wait I can access the script that the script is deriving from?
(or you could emit events/messages but that's a little messy, maybe)
public class Player : MonoBehaviour
{
[SerializeField] private Head Head;
[SerializeField] private Leg Leg;
private void Awake()
{
Head.Init(OnLegShakeComplete);
}
private void OnLegShakeComplete() => { .. leg shake is done .. }
public void OnStartLegShake() => Head.StartLegShake();
}
public class Head : MonoBehaviour
{
private Action _onComplete;
public void Init(Action onComplete) => _onComplete = onComplete;
public void StartLegShake() { .. animate leg shake then call OnComplete ..}
private void OnComplete() => _onComplete?.Invoke();
}
little sloppy but maybe that describes it
"player" has a head and a leg, tells one to do something, gets a message when that thing is done
i probably wouldn't do it that way though - I'd just have all the animation components in one script so it can have the state internal to "one thing" and not have to do all this talking between components
I'm using the StandardAssets scripts as a base, just splitting it up into separate scripts
The First person controller script
nvm
Like able to put a URL in the text box and it will play the video and audio
Why not use the unity video player component for that?
Using it for vrchat world I'm making . . .
That doesn't answer my question
bump (i posted updated script in below messages)
there's no button or anything to interact with it
this is what im trying to do
The video player component would only play video. It doesn't provide any ui. If you need ui, you'll need to implement it yourself.
*in addition to the video player component
I have a problem; I don’t know if anyone can help me. I’m subtracting 0.2 from a value, but when I reach 0, it becomes 2.980232e-08. When I subtract again, it goes back to 0. I have a clamp with a minimum of 0 and a maximum of 1
Floating point error. The xxxe-08 number is a very small number in a scientific notation.
Before you subtract 0.2, it's probably something like 0.20000001 or something like that.
When adding 0.2 from 0, you smoothly transition to 0.2 and beyond, but subtracting can lead to small floating-point errors, resulting in values like 2.980232e-08 instead of 0, while going directly back to 0 from 0.2 works as expected.
that's why im confused
That number is essentially 0 as dlich wrote above. You could just use something like Mathf.approximately to check if it's close to 0 and set it to 0
Floating point math(both adding and subtracting) would inevitably lead to a floating point error. You need to design your systems such that they take that into account.
are you sure maybe you're not going under 0 ? maybe it throws the whole thing off
can also try currentValue = Mathf.Max(currentValue - amount, 0);
nvm audiosource already clamps the value below 0
yeah I'm trying to transfer that to udon graph
im using execute always attribute and im moving a handle in editor code which means im regenerating a mesh but my update function doesn't seem to always get called every time i make a change so when im moving the handle the mesh isn't very responsive in terms of updating, what exactly triggers the update method in monobehaviours when using execute always when not running*
it works fine at run time since update is called every frame no matter what but doesnt seem to be the case in edit mode
hi, i am using addressables to load and unload scenes. Addressables.UnloadSceneAsync unloading the scene properly, but every time i load and unload, some usage in Untracked section of memory profiler adds up. The code is simple, any help would be great for me
Here’s the code:
public AssetReference sceneRef;
AsyncOperationHandle<SceneInstance> handle;
private void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
handle = Addressables.LoadSceneAsync(sceneRef, LoadSceneMode.Additive);
}
if(Input.GetKeyDown(KeyCode.S))
{
Addressables.UnloadSceneAsync(handle, UnloadSceneOptions.UnloadAllEmbeddedSceneObjects, true);
}
}
i am tired of posting this same type of addressables untracked memory related questions...still no way to go. any help please?
How do I make a variable visible but not editable in the inspector?
With a custom editor or naughty attributes:
https://dbrizov.github.io/na-docs/attributes/meta_attributes/read_only.html
https://dbrizov.github.io/na-docs/attributes/drawer_attributes/show_non_serialized_field.html
Serialization has a cost, it's usually best not to serialize unless you actually intend to use it.
You can also just use the debug mode in the inspector
true, saving them inside serializable objects isn't free per se, but the cost is negligible, especially for the workflow increase
Not to mention that when you build, its trivial to just undo the serialization
I'll probably end up just using naughty attributes
There will always be cases where its too custom to be activated all the time. Why do you want to expose the value if you not gonna use it through inspector anyway. I guess, its either for others to use your "tool" and know visually whats going on or for debugging purposes?
bump (i posted updated script in below messages)
IEnumerator LoadSceneRoutine(int sceneIndex)
{
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(sceneIndex, LoadSceneMode.Single);
while (!asyncLoad.isDone)
{
yield return new WaitForEndOfFrame();
}
Transform foo = FindObjectOfType<Transform>();
}```
Why does the last line throw a NullReferenceException? I want to find some objects in my new scene after loading.
do you have it in your scene? the transform type?
that line will not throw a null ref exception
The line should not throw the null reference exception by itself
Please, show the stack trace
NullReferenceException: Object reference not set to an instance of an object SceneHandler+<LoadSceneRoutine>d__7.MoveNext () (at Assets/Scripts/UserInterface/StartMenu/SceneHandler.cs:43) UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <0b78209fd00d4f419f30dd210cbab239>:0)
It's not about the last line
The object containing the SceneHandler is a singleton that is in "DontDestroyOnLoad" though, might this cause the issue?
The exception is thrown when moving IEnumerator
What do you mean by that?
I mean that it's throwing when calling IEnumerator's MoveNext
Since it can only be thrown on start, it's most probable that the scene on the index is not found
Hold on I was being an idiot
Never mind
.>
Spent 30mins programming and forgot to connect one reference via Editor.
well, anyone into that?
Is the scene empty, you are adding there. Or does it also happen to an empty scene?
never did such thing with empty scene, there are some objects in the scene, not adding anything after it is loaded
Just wondering if you are referencing anything inside of it or if any texture is still loaded. Did you let it run for a while and see if GC kicks in at some point
I dunno what documentation I was looking at but I'm glad I can just InputActions.FindAction instead of whatever hellish setup I'd found a year ago lol
nothing is referenced, just one object with a material, not even any texture...i waited for some time, the untracked memory is still there
So try it with an empty scene without anything and see if that happens too to track the source of the untracked memory
i'll do it, thanks
Hey so i am trying to calculate the normals of these bumpers, so i have full controll over my object to bounce in the correct direction
the gizmo line is my current trial and error lol
So those are 3D objects?
no its 2d. and im trying to use rigidbody.addforce
Did you try simply transform.up?
yes, but that points to the middle of the screen
i want it to point in the direction of the bumper
Show your code/what you tried
the goal is for the lines to show in the correct direction. so straight up for the left bumper, straight down for the right, ok?
Yeah.
This sounds like you did something wrong
the code itself is not interesting. its just a gizmo and rigidbody.addforce
Did you perhaps use DrawLine with a position and a direction, while it expects two positions
i use the gizmo to debug my trial and error
var y = transform.localPosition.y;
var cross = (transform.position.x - x / transform.position.y - x);
Gizmos.DrawLine(transform.position, new Vector2(cross, y - transform.rotation.normalized.z));```
thats my current approach
but ive tried many things already,
You did this^
vector.up, vector.zero. I tried to substract the position from the transform.localpos
Use Gizmos.DrawRay instead (takes a pos and dir) or convert your second argument from a dir to a pos
i tried to use drawray, but couldnt see lines :/
Show what you tried
Gizmos.DrawRay(transform.position,Vector2.up);
i might have used vector3.up before
which could be why. now im seeing the line
This is incorrect:transform.rotation.normalized.z
You are accessing rotation which is a Quaternion.Using its z value here is nonsense
Just do Gizmos.DrawRay(transform.position,transform.up);
so addforce documentation says "Force is applied continuously along the direction of the force vector. "
and the code is public "void AddForce(Vector3 force, ForceMode mode = ForceMode.Force);" so i guess i can use the same vector from my gizmo debug in the addforce function
Yes, both work in world space so the direction is the same
so while the gizmo accepts a from, to vector, the addforce, only accepts one vector
it appears to work better now, thanks
Yeah, but the "from" vector in addforce is the position of the rigidbody itself
There's always AddForceAtPosition if you need
yeah i found out it was obvious as well lol.
didnt knew that thanks
I wanted to use navmesh to get the path but move my NPC along it with its own movement method.
how's the best way to do it? should I just grab the path and manually check distance /move to each point
I am currently facing an issue. This class I posted here was meant to take a custom script through the <T> value and show all of its methods able to be called. But the issue is, the more scripts I want to attach to this, I need to create multiple custom inspector inheritances for it. So I thought, I could just drag drop a script from the assets and take its type to use reflection against. But somehow, instead of my actual class Singleton<T>, I only get unityengine.monoscript and therefore limited methods. Anyone know the issue here?
#if UNITY_EDITOR
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace MyNameSpace
{
public class ClassMethodEditor<T> : Editor
{
int selected = 0;
readonly List<string> allMethods = new();
Object reflectedClass;
SerializedProperty currentMethod;
private void OnEnable()
{
currentMethod = serializedObject.FindProperty("currentMethod");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
reflectedClass = EditorGUILayout.ObjectField("Referenced Class:", reflectedClass, typeof(Object), false);
if (reflectedClass != null)
{
var flags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public;
Debug.Log(reflectedClass);
allMethods.Clear();
reflectedClass.GetType().GetMethods(flags).ToList().ForEach(m => allMethods.Add(m.Name));
///All the other shizzle to assign the currentmethod, not important for this issue
}
else
{
Debug.LogWarning("Reflected class is null");
}
serializedObject.ApplyModifiedProperties();
}
}
}
#endif
When you reference a script itself, rather than an instance of the component on an object, you get MonoScript. It's literally a reference to the C# code file.
Of course if you want to get the actual class the code iside MonoScript defines there's this:
https://docs.unity3d.com/ScriptReference/MonoScript.GetClass.html
using MonoScript directly instead of UnityEngine.Object will make your code cleaner too btw
EditorGUILayout is not a big fan of monoscript 😉 But thanks a lot, that getclass() method was, what I needed! awesome and already working 🙂
Ah never mind, casting as Monoscript was missing, my bad
any particular reason why you wrap the class in the #if rather than putting it in an Editor folder?
Nope, not really. Guess it grew with the whole framework I am working on and just stayed there til now and as I hit build, the issue appeared with editor scripts not available on build. But will move it right now, thanks for pointing out 😄
Now I can grab any script and just call methods , nice 🙂
I am not 100% what you need this for but I can recommend just creating editor windows with one button per function, easier than having to drag & drop that in there and then looking in the dropdown for the function you want to execute 😄
If you for some reason own odin already that is as easy as adding a [Button] tag 😄
I assign this script to my ui buttons and just call "CallMethod" on the buttons everytime. This way I can just call for global methods on Singletons without the need to reference them in code or via drag drop
Imagine a global system and you want to trigger a state from a prefab button inside a user menu. That menu only gets instantiated on specific users and so on. you dont want to write a script for every case or hard set anything. So I just drag my singletons in, get the methods and am able to call global methods easily
Then you can instead assign your target script directly to the gameobject and tag your function with [Button], removes the need for a proxy 😄
class Helper : MonoBehaviour
{
[Button]
public void DoSomething()
{
UnityEngine.Debug.Log("TEST")
}
}
attach that to anything in the hierarchy and you get the button in the inspector
Nope, not my issue here. I do not want to call the function from inpsector. Its a UI Button in runtime
ah that makes sense
But then again make the XRAnchorManager a monobehaviour, attach it anywhere and drag it into the onClick callback field of your button
also lets you pick the executed function from a dropdown
you should read more careful, what I wrote. How do you achieve this with an instantiated prefab?
I am calling this method on runtime on the instance of the anchor manager. But need to use reflection to get it everywhere in editor
You can grab the next navmesh position using NextPosition
https://docs.unity3d.com/ScriptReference/AI.NavMeshAgent-nextPosition.html
How do i access the panels rect tranform right stretch?
alr ty
Hi everyone!
I have a "level system" in which the player walks and once it reach the end you can deliver some items to complete it.
Right now i have a scriptable object for each level telling which items to deliver and how much to give for each item. So if i have 100 levels i need 100 scriptable objects.. is this the best way to handle it or i can do it in a different way?
The scriptable object holds reference to the items (which are other scriptable objects so i can get the relative info about it)
It's considered better to store your data as jsons
So, you'll have it as a serializable class or struct converted to json
better by what metrics? if this is just data you're editing in editor, what's wrong with scriptable objects?
Since they've mentioned referencing the items, it's better to use jsons for every level with them referenced than hundreds of scriptable objects
what's the benefit of using JSON there?
What's the benefit of using scriptable objects here?
It's better to have a class serialized in the inspector, which is then parsed to json
I would not only consider it more convenient, but also more efficient
well, you're the one who said json was better, i don't see a huge difference except json is more work to implement 🤷
Would you be able to see the difference with a thousand scriptable objects created?
Id suggest, if you are using references throughout the project with custom textures and what not and they do not change at runtime, use scriptable objects. If you are just changing values for each level, like amount of items, go with some json approach, as you can easily extent, rearrange or whatever without having to fiddle around with actual file assets.
the difference here isn't one data format vs another, it's whether you create separate scriptable objects for every individual item, which you obviously don't have to do!
Since you usually store levels inside of separate json files e.g. Level 1.json, Level 2.json etc., it would be better to put everything related to it inside of it, including the item referenced mentioned by the op
Why would you put every level in a single json file?
JSON would hold an array of levels you get from for example ONE single scriptableobject, that holds all levels as an array or a database / backend, you name it.
if deserializing 100 json files at runtime is acceptable you could keep them separate, but i'd probably want to compile them into one big asset for the build
ok yes, the json was my other option. Thank you! I was just wondering if these two were the best approach because i was bothered by the "too many things to do" but i guess its just the gamedev experience then!
Since i have to show the image of the item i should use scriptable object then
Do you want to put all levels into a single json file?
It's acceptable when the entire level data is needed on level load
Thats what json is commonly used for. arrays of objects, in this case, level information
Do you want to deserialize all levels at once?
oh thats true too
it's pretty convenient to do it that way if you want them to directly reference assets, if you're worried about performance you probably want to profile it before making any big decisions
but this would happen right if i use json. But with scriptable object i still need to reference in a list all the levels. so i guess the end result is the same just with a different starting point
cause i have a List of scriptable object so i can easly go from one level to the next by just increasing the counter
I think this discussion is out of the scope of the actual question asked. The leveldata is always simple values or referenceIDs to assets. You dont want to put images as base64 in it or whatever. So its basically a textfile. You are fine loading the levels in one json then.
I was referring to them willing to put all levels into a single json file, not having every level in a separate one
and if i want to add another level i just create a new one and add to the list
yes yes, no way i would put all the levels into one scriptable! 😂
Then it would be more appropriate to say "loading all level references into a single json"
Okay, this discussion turns into "I want to be right"... I am out of this.
whatever works for your game, be it scriptable object or json, is the "best" solution man
yeah it really depends mostly on what workflow you prefer in the editor
if i have a json with all the level how can i reference the item i need in it
scriptable is easy cause i just create a variable with the itemData
i need to store the reference of each item in something like a dictionary and access through keys
You do not author the items in the json file. you create a json file from whatever datasource you have.
so im wondering what would be the best, storing every item and then accessing through the json or using only the item i need in the scriptable.
pro of json is having one file at cost of a bit of memory
pro of scriptable is accessing directly to that reference without using extra memory at cost of many many scriptable objects
if you want to edit the objects directly, it's hard to beat scriptable objects for convenience, otherwise you need some kind of ID system so you write those in your json and look them up at runtime
deserializing 100 json files during runtime (not sure why though, probably just need the one for your current level?) would take like a 30-100ms tops unless they're 100mb-gigabyte huge and you're on a hard-drive
Id say, you could mix them up, as you want to easily throw levels around in order, make your level list a json and make your levels scriptable objects, if you need references to different project assets
correct me if im wrong ofc!
yeah, but the memory cost of 100 scriptable objects is also negligible on modern devices, so we're really splitting hairs
But again, it depends on your whole setup, amount of levels and what not
actually that would happen only once in the start (or awake) so doesnt matter the time it needs
you'd only be using json if you want to provide the user with the ability to modify things after build, scriptable object wouldn't be great here for that case