#archived-code-general

1 messages · Page 373 of 1

hexed pecan
#

Depends on your design, you could also incorporate those in the flags just like other weapon types

solid relic
#
[System.Flags]
public enum Weaponry
{
   Gun = 1 << 0,
   Melee = 1 << 1,
   noGun = 1 << 2,
   noMelee = 1 << 3
}

Something like this yeah?

hexed pecan
#

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

timber finch
#

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.

solid relic
# hexed pecan Anyway, you can think of enum flags functionally as an "array of booleans", spec...

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

hexed pecan
solid relic
#

It's like the phasmophobia evidence journal if you've ever played that

hexed pecan
#

I haven't, but I see your idea

timber finch
#

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

cosmic rain
solid relic
solid relic
timber finch
#

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?

hexed pecan
cosmic rain
solid relic
timber finch
#

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

short quiver
#

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

solid relic
#

Rather than this then, how would it look based off of what you're saying? @timber finch

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;
    }
}
short quiver
#

@solid relic @timber finch thread please

cosmic rain
dusk apex
short quiver
#

Since I described the way of using

high otter
#

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);
mighty yew
#

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"?

cosmic rain
mighty yew
#

i fully believe that, how do i do that?

hexed pecan
#

In a similiar way as you assigned the vertices, but with a list of Vector2's and SetUVs

mighty yew
#

What would the vector2's be?

hexed pecan
#

The UV coordinates. They tell the shader what part of the texture goes into what part of the mesh

dusk apex
high otter
#

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..

grizzled herald
#

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??

quartz folio
unique delta
#

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?

lean sail
unique delta
#

I know is something from the main scene because i use the same script to load other scene and it works perfectly.

lean sail
unique delta
#

i ll send a video i have to commpres it first

lean sail
knotty sun
#

A video tells us nothing, you need to debug your code and then show the code and the logs

unique delta
teal quarry
#

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 ?

lean sail
teal quarry
compact perch
#

Sounds like work for an ISpawnMethod interface and/or strategy pattern or smth like that

lean sail
# teal quarry Scalable in the sense that when a new spawning way is added, it should not modif...

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.

teal quarry
jovial quarry
#

Clear and easy to add new way of spawning

compact perch
#

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

lean sail
# compact perch you could also mess around with some delegates. Either way i think following sol...

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.

compact perch
#

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

gleaming summit
#

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?

compact perch
#

it is super-wide question

lean sail
# gleaming summit I had an Idea for a great Game mechanic in Unity 2D but have not Idea for a solu...

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".

rough fern
#

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

lean sail
elder marsh
#

i have two positions Vector2 and i want to convert these two positions to a float rotationInDegrees. how would i go about doing this?

dusk apex
#

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.

elder marsh
#

was looking for a angle function in vector2 and nothing 😵‍💫

dusk apex
elder marsh
#

oh... i wonder if i had system.numerics then 🤔

#

yes... yes i did

dusk apex
#

If you were following a tutorial (Brackeys and others on the net who are using such practices), they've simply made a mistake.

rough fern
dusk apex
#

Reminder that GetAxis with "Horizontal" and "Vertical" are fine (using Time.deltaTime) but not "Mouse X"/"Mouse Y".

quick glade
#

@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)

dusk apex
quick glade
#

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

rough fern
dusk apex
#

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.

quick glade
rough fern
quick glade
rough fern
#

Like in Tarkov?

quick glade
rough fern
#

Since I don't know how it works ik pubg

quick glade
dusk apex
#

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.

rough fern
#

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

quick glade
#

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 tenkaGul

lean sail
quick glade
rough fern
#

Or first solve as much of the issue as you can yourself to learn how it works

rough fern
lean sail
#

and you can always add your own functionality on top of it

rough fern
#

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

quick glade
#

thanks it works

rough fern
quick glade
#

the change i saw is
character.Rotate

#

is this the problem?

rough fern
#

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

quick glade
#

roger that thanks for your time friend tenkaZyumruk

rough fern
#

No problem, good luck with your game

low rapids
#

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

leaden ice
compact perch
#

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

rough fern
leaden ice
#

Tbh learn your IDE's hotkey for commenting and uncommenting

#

It's the fastest way

low rapids
rough fern
low rapids
rough fern
leaden ice
low rapids
#

Thanks

compact perch
#

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)

fresh cosmos
#

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?

steady moat
fresh cosmos
#

do i need do use the callback for something or? what does that do?

#

or what can it do?

steady moat
#

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.

stone pewter
#

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?)

hexed pecan
#

I don't know why but according to docs it is intended 🤔

hexed pecan
stone pewter
#

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();
    }
}```
swift aspen
#

Probably fine if you assign back the old event after, just so you dont break anything down the IMGUI line

stone pewter
#

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 pensivebread

swift aspen
#

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

stone pewter
#

hmm ok

rigid island
#

for editor scripts
UIToolkit > IMGUI

stone pewter
#

unfortunately this is a hybrid meant to be used both at runtime and in editor. the scene view, specifically

hexed pecan
#

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

rigid island
fresh hazel
#

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?

hexed pecan
stone pewter
rigid island
rigid island
#

where it says Use C# script to add UI controls

hexed pecan
#

Is it common to use UITK for ingame UI? Not editor

#

I dislike the gameobject based UI too so I'm considering that

rigid island
#

they are pushing it but tbh ive yet to see it

thick terrace
#

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

rigid island
#

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

hexed pecan
#

Is it stable though? Any major issues?

thick terrace
thick terrace
hexed pecan
#

I see

thick terrace
#

until they have world space support we can't touch it for game stuff anyway

rigid island
#

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

stone pewter
#

does UITK have things for more interactive stuff like detecting mouse movement and custom capture mouse events without having a control under the cursor?

hexed pecan
#

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 🤷‍♂️

rigid island
#

isn't that already built in the Editor class somehwere

stone pewter
#

not sure! I need it outside the editor in this case

rigid island
#

ohh right I think you mentioned this also being used in Runtime ?

stone pewter
#

yeah

somber nacelle
stone pewter
#

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

rigid island
fresh hazel
#

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();
            }
        }
rigid island
#

Destroy(gameObject, myTime);
oh wait I see its WaitForEndof frame

fresh hazel
#

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

dawn nebula
#

My brain is not active right now. Can someone tell me why these two groups of code result in different rotations?

native copper
#

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 ...

▶ Play video
pallid bough
#

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

somber nacelle
#

not a code question

pallid bough
#

where would I ask this then

somber nacelle
marsh spade
#

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

somber nacelle
#

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

neon glen
#

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

neon glen
knotty sun
somber nacelle
# neon glen i dont though

That doesn't mean there isn't another definition for StarterAssets, that just means you don't have another asset called StarterAssets

turbid loom
#

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

neon glen
somber nacelle
#

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

neon glen
#

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

somber nacelle
#

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

neon glen
somber nacelle
#

that depends on how your PlayerInput component is set up

native copper
lean sail
pure ore
#

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"

rigid island
rancid frost
#

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?

boreal cloud
#

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

rancid frost
#

that usualkly happens when you set the ortho size to negative

boreal cloud
#

this is using a perspective camera

rancid frost
#

might be thesame case, not sure

boreal cloud
#

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;```
hexed pecan
rancid frost
#

zero

rancid frost
hexed pecan
#

Sounds like you are generating the chunk in world coordinates then

#

Would need to see that code to help further

rancid frost
#

hmm, it most likely true

simple ruin
#

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

vapid lynx
#
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.
grizzled sand
#

Hello I need someone who knows how to use Unity very well for realistic firearm models and realistic military equipment

grizzled sand
#

I don't understand can you repeat

naive swallow
grizzled sand
naive swallow
#

This is a server to ask code questions. What is the actual question

grizzled sand
vagrant blade
tawny elkBOT
#

: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

vagrant blade
#

But word of warning, nobody wants to partner with an "idea" person. Good luck.

molten zinc
#

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

lean sail
molten zinc
#

ill attach it in a second

spare dome
#

!code

tawny elkBOT
molten zinc
spare dome
#

are the walls slanted in any way?

molten zinc
lean sail
#

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

simple ruin
#

shoot mb

vagrant moon
#

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 ?

warm badger
#

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
        }
    }
}
rigid island
rigid island
#

thats why you typically don't use them for save systems or anything

warm badger
#

then is there anything alternative

rigid island
#

just save into a file?

cosmic rain
warm badger
vagrant moon
#

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

void basalt
vagrant moon
#

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

cosmic rain
#

Where does it create the files? What does the generator code look like? What do the generated files look like?

vagrant moon
#
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

cosmic rain
#

It's not obvious, especially considering not everyone here has experience using source generation on daily basis.

cosmic rain
void basalt
vagrant moon
#
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
    });
}```
void basalt
#

no, I thought you were talking about the actual generator itself

vagrant moon
#

do we use here any specific side to share bigger pices of code than few liners ?

cosmic rain
#

!code

tawny elkBOT
vagrant moon
#

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.

vagrant moon
#

😮‍💨

cosmic rain
vagrant moon
#

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 :/

cosmic rain
vagrant moon
#

its unity package thou :S. its not detached project.cs /solution .sln its in my com.ducknest.---...

swift falcon
#

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?

cosmic rain
swift falcon
#

this is my profiler

cosmic rain
swift falcon
#

im not

#

im new to unity

#

what is tha

void basalt
#

are you using 3rd party scripts that might be doing that?

swift falcon
#

no i followed a tutorial and the game runs fine in the editor and then runs bad after a few seconds in final build

void basalt
cosmic rain
swift falcon
#

how can i check

void basalt
#

post the script

#

!code

tawny elkBOT
swift falcon
#

which script i have multiple in the project

cosmic rain
# vagrant moon

The asmdef in your package also makes sure it's a separate assembly.

void basalt
swift falcon
#

when i built the game

#

at the end of development

#

its a super simple flappy bird clone too

void basalt
#

did you try restarting the editor

swift falcon
#

its a separate build, nothing to do with the editor but ill try exiting all of it

void basalt
#

oh I misread what you said. I thought you said it was happening only in the editor

swift falcon
#

no only in the buildf

cosmic rain
swift falcon
#

in the unity editor?

void basalt
#

in your code

#

in any script

swift falcon
#

i never wrote that in any of the scripts so what do you mean?

cosmic rain
swift falcon
#

not there

void basalt
#

turn vsync off perhaps

swift falcon
#

vsync off in the build settings?

void basalt
#

sure

swift falcon
#

i dont see that as an option

void basalt
#

quality settings

swift falcon
#

and where is that?

void basalt
#

you can just open project settings and type vsync into search field

swift falcon
#

can you hop in a call with me?

void basalt
#

no

swift falcon
#

okay where is project settings

void basalt
#

edit -> project settings

cosmic rain
#

With all these questions you should really go over the basics of using unit: !learn

tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

swift falcon
#

this is what showed up

void basalt
#

well it showed up. so its somewhere in there

swift falcon
#

vsync count is set to every v blank

void basalt
cosmic rain
swift falcon
#

okay i set it to dont sync

void basalt
#

idk why vsync would be locking it to 15 fps, that's strange. but its worth a shot

swift falcon
#

that fixed the issue

void basalt
#

lol

swift falcon
#

so we don't know what that means?

void basalt
#

vsync usually locks it to your monitors refresh rate

#

do you have a 15hz monitor?

swift falcon
#

no lol

#

144

#

turning vsync off also helped me in other games in the past

#

like playing them i mean

void basalt
#

I mean vsync works fine for me especially with gsync

#

I play with it on in everything

cosmic rain
#

Might be something wrong with your hardware or OS/drivers or their settings.

swift falcon
#

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?

void basalt
#

leave it up to the user

#

add a pause menu setting

swift falcon
#

so for every game i make i need to account for that just because my computer is weird

cosmic rain
swift falcon
#

yeah but im confused

void basalt
#

if you have a gsync monitor you also need vsync on for it to work properly

swift falcon
#

i do have a gsync

#

but its hdmi not display port if that has to do with anything

void basalt
#

dont use hdmi for 144hz lol

#

use displayport

swift falcon
#

ik it goes down to 120

#

but im just lazy atm

void basalt
#

I would test that next if you really want to figure it out

swift falcon
#

either way it shouldnt affect my unity game

#

i think it wont affect other users

#

just me

#

because i have vsync on

void basalt
#

🤷‍♂️

swift falcon
#

maybe i should check my vsync drivers if thats a thing

cosmic rain
swift falcon
#

still, thank you @void basalt

swift falcon
#

@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

wispy thistle
#

Any ideas how i would clone a object and store it in an array

ocean hollow
wispy thistle
#

Using c# ? And what if there objects with the same name

ocean hollow
#

unity only uses c#

#

idk what u mean abt them having the same name

#

theres no problem

rose fulcrum
#

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?

rose fulcrum
#

nvm solved it. I've come full circle. I can't seem to prevent a new line when I submit.

next sparrow
#

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)

azure frost
#

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?

sharp temple
#

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

lean sail
lean sail
mellow sigil
#

Post the !code as text 👇

tawny elkBOT
lean sail
sharp temple
#

alr so should i send the code instead?

sharp temple
#

!code

tawny elkBOT
sharp temple
#
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);
        }
    }
}
dusk apex
#

Post it using the large code blocks guide (via the links provided)

sharp temple
#

ok

#

im using a character controller to move the player

#

if u need the movement code i can provide it

lean sail
# azure frost Okay, how do I do that?

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.

mellow sigil
azure frost
sharp temple
#

ill try late update

azure frost
arctic sparrow
#

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

lean sail
# azure frost Basically, the method I'm hoping for is this. ``` Any force that is applied to t...

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.

sharp temple
arctic sparrow
#

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.

mellow sigil
#

It makes sure that the camera has already moved that frame. So move camera -> move object instead of move object -> move camera

thin aurora
#

.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

upper pilot
#

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?

fleet gorge
#

coroutine-related functions are from unity's monobehaviour because they rely on the update loop

leaden ice
upper pilot
#

Thanks, I will either pass Action or do it from monobehavior side

cold parrot
hexed pecan
#

I dont see the problem in the solution they already figured out

next sparrow
next sparrow
next sparrow
# cold parrot You may want to google ZLogger, Serilog, NLog and log4net.

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.

hexed pecan
#

Yeah, no need to pollute your codebase/project with external stuff when you can do something as simple as that.

lean sail
hexed pecan
#

That's also true. I don't see why the generics, object would be enough

thin aurora
#

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

lean sail
#

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"

thin aurora
#

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

still gust
#

Does anyone know some good resources for getting started on combat systems? I'm not really sure where to start

rigid island
wind frost
#

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?

still gust
leaden ice
still gust
rigid island
still gust
rigid island
#

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

still gust
#

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?

rigid island
#

yeah sure lol

still gust
#

aite ty :^)

rigid island
#

the real choice would be, do you go with Inheritance or Composition, or maybe both

still gust
#

ive actually never heard of composition ive used inheritance b4

rigid island
#

Inheritance
Sword : Melee : Weapon
or Composition (also making specific components)
IWeapon or IMelee

#

etc

still gust
#

would u say the composition approach is useful?

#

oh wait

#

is composition just interfaces?

rigid island
#

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

raw ocean
#

hey there

#

ill go straight to the point

#

i have problems with the animator

#

anyone mind helping me out?

knotty sun
#

you can start by not pressing enter every line

raw ocean
#

but sure ill try this one

still gust
leaden ice
rigid island
still gust
#

thanks for your help ill try it out :^)

rigid island
#

np. Goodluck in your journey 🙂

inner shuttle
rigid island
wind frost
rigid island
wind frost
rigid island
wind frost
rigid island
marsh spade
#

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;
    }
}

knotty sun
marsh spade
#

oh whoops im sorry, i miss clicked i thought I was in beginner

lone bone
#

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.

stoic ferry
#

I need some help

knotty sun
tawny elkBOT
gloomy osprey
#

how can i find what Vector3 is about 85% of the way between 2 different Vector3's?

rapid notch
#

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

hexed pecan
#

I understood that they need a vector 85% between two points, where Lerp is the correct tool

solar wigeon
#

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)

hexed pecan
solar wigeon
#

wait i just realised that

dusk apex
#

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.

solar wigeon
#

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 ?

hexed pecan
#

Did you move the if statement outside like Dalphat suggested? That should fix it.

hexed pecan
#

Otherwise after the first iteration, you have changed readyForNextShot and in the next iteration you can't shoot

solar wigeon
#

it worked red_tick

dusk apex
stone rock
#

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.

inner shuttle
#

wait im a numpty

next sparrow
next sparrow
next sparrow
next sparrow
vapid lynx
#
    {
        
        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

lean sail
lean sail
next sparrow
# lean sail 🤦‍♂️ it works but if you refuse to show the actual error and code you had at th...

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!

gloomy osprey
#

player.transform.position = Vector3.Lerp(player.transform.position, Trailer.transform.position, 0.85F);

#

the result was equal to Trailer.transform.position

dusk apex
# gloomy osprey 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.

gloomy osprey
dusk apex
#

You've probably got something else going on. It should definitely not give you identical results.

gloomy osprey
#

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

dusk apex
#

Try logging the position before and after lerp.

#

The result you see from the inspector may be due to something else

gloomy osprey
#

alr

gloomy osprey
short quiver
#

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

vagrant blade
#

Because time isn't flowing? How are you moving your object?

broken light
#

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
haughty umbra
#

how does one make a video player from scratch using ui?

worn star
#

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

cosmic rain
cosmic rain
solar wigeon
#

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

quartz folio
#

Why are you using the y co-ordinate twice

solar wigeon
#

because i even tried Direction.x it didnt work

solar wigeon
#

any ideas for the question ?

mellow sigil
#

Usually the reason is because the movement code overrides the recoil

solar wigeon
#

lemme sent the code

#

!code

tawny elkBOT
solar wigeon
#

this ⬆️

mellow sigil
#

right, the movement sets the x velocity directly which overrides whatever the recoil code does

solar wigeon
#

so any ideas how to fix it ?

mellow sigil
#

Start using AddForce instead of setting the velocity directly

solar wigeon
#

same thing happening

mellow sigil
#

Everywhere, not just there

solar wigeon
#

wai lemme try something

solar wigeon
mellow sigil
#

Your movement code overrides all other forces. You have to change the movement code.

solar wigeon
#

in which sense then how will move my player

mellow sigil
#

with AddForce

solar wigeon
#

oh

#

something like this ?

mellow sigil
#

Something like that, except you have to multiply by Vector2.Right as well

solar wigeon
#

rb.AddForce(Vector2.right * horizontalInput * Speed, ForceMode2D.Force); like this ?

#

it works now everything is slippery

mellow sigil
#

You'll have to tweak things like drag and friction

solar wigeon
#

should i do something like this ??

mellow sigil
#

I would start with drag and friction but you'll have to experiment what works best

solar wigeon
#

like materials ?

#
    private void Drag()
    {
        if (grounded)
            rb.drag = GroundDrag;
        else
            rb.drag = 0;
        
    }
``` ?
mellow sigil
#

Friction is in materials, drag is in rigidbody

raw ocean
#

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)

quartz folio
#

You probably have multiple instances of the script in the scene

raw ocean
#

the cube on the right for example

#

is supposed to open and close

#

if the door is closed the lights go off

quartz folio
#

Well every instance will need that variable assigned

#

Search the scene for the script and make sure they all have it

raw ocean
#

every button and door has the script propely connected

#

with the items and objects assigned

mellow sigil
#
if(Light == null)
{
    Debug.Log(name + " doesn't have Light assigned", this);
}
#

Put this in Start

raw ocean
#

Oh wait

solar wigeon
raw ocean
#

i found out the issue

#

thx for help everyone

rotund burrow
#

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.

frigid latch
# rotund burrow Hi, i want to organize my code for projectiles better. I have an abstract projec...

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.

somber nacelle
#

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

somber nacelle
frigid latch
sweet verge
#

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?

rigid island
solar wigeon
sweet verge
#

not every frame

rigid island
#

btw SerializeField exists, you tehcnically can go without needing GetComponent (assuming you don't want a component at runtime like a raycast)

sweet verge
#

I already use [RequireComponent

rigid island
#

why not ? its good to have everything locked in

sweet verge
rigid island
#

all it does it add a component

sweet verge
#

having it as serialized actually makes it too flexible. Now I can put random stuff in the field

rigid island
#

it doest GetComponent for you

rigid island
sweet verge
#

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

rigid island
#

it doesn't but less time wasted fetching component when its already there

sweet verge
#

its already there because of RequireComponent

#

so then I do GetComponent to get it

rigid island
#

GetComponent has its own cost

sweet verge
#

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

rigid island
#

so what happens if you have TWO of the same type on the same object?

sweet verge
#

you can put two components of the same type on a single object?

rigid island
#

no limit to how many of the same type can go on gameobject, yes

sweet verge
#

hm when would I do that

#

like i would never put 2 character controlelrs on a game object

rigid island
#

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

rigid island
#

line 48 is landing on { so make sure you sent the updated script

royal wigeon
#

Are singletons for something like the player object worth it in a singleplayer game or should I stay away from it.

cold parrot
royal wigeon
rigid island
cold parrot
solar wigeon
rigid island
solar wigeon
#

!code

tawny elkBOT
solar wigeon
cold parrot
solar widget
#

im a newbie

mellow sigil
#

The message is not coming from this script

solar widget
#

how would i know where its coming from

#

im very clueless

inner shuttle
#

click on the error message and it would show you

solar widget
#

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

mellow sigil
#

Did ChatGPT write this script?

solar widget
#

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

inner shuttle
#

the comments on the first one gives it away i wont lie

#

plus some of the code is questionable

solar widget
mellow sigil
#

If you had wrote that message in the script you'd know where it is

solar widget
#

yea... i have no idea

#

i was just forced into doing a project which i dont want to do 😭

mellow sigil
#

We can't help with GPT-generated code

solar widget
#

i understand

#

thank u though

#

do u know what i should do next since it cant be helped?

inner shuttle
#

reset it and write it yourself

frigid latch
#

wtf chatGPT-generated code used GameObject.Find like that? Omg that's horrible code

frigid latch
solar widget
#

sadly i dont have much time to learn as this is due in like 2 weeks

knotty sun
potent anchor
#

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

solar widget
knotty sun
# solar widget tons

so don't you think it's a false economy not to learn, do yourself a favour, learn

spare dome
tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

knotty sun
#

you can learn to debug in 2 hours

spare dome
#

true

potent anchor
#

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

crude creek
#

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!

knotty sun
tawny elkBOT
crude creek
knotty sun
crude creek
#

ooh I see

#

lemme change that

#

thanks!

#

I'm sorry but it is still happening...

mellow sigil
#

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

open plover
#

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?

crude creek
#

Found it, tanks!

sonic trench
#

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

sonic trench
#

I guess I could instantiate a wave script to hold the wave data and keep multiple inside a list?

knotty sun
sonic trench
# steady moat You can do it that way ?

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)

steady moat
#

You can then have your spawn script iterate all wave and spawn them accordingly.

sonic trench
#

Yeahe

#

Alr Ill try this

#

its a bit different than what i did

#

Thanks yall

wooden spruce
#

Does anybody know the encryption method for .dat save files for mobile unity games?

wooden spruce
inner shuttle
#

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

dusk apex
inner shuttle
#

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

dusk apex
#

I'm not sure what you're referring to by visual spinner

inner shuttle
#

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

dusk apex
#

Maybe when you're about to drop an item, reference it first then spin. Finally drop the previously referenced item.

inner shuttle
#

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

dusk apex
#

Right. The code simply sets the next item active and doesn't do any spinning.

inner shuttle
#

yes

dusk apex
#

So spin it - we haven't seen your spinning implementation yet.

inner shuttle
#

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

dusk apex
#

Show your spin implementation

inner shuttle
#

give me a min i need to put it back in

dusk apex
#

How are you spinning outside of item removal?

inner shuttle
#

arrow key presses and im just rotating it by 90f and also incrementing heldItemIndex

dusk apex
#

Alright. Well, there isn't enough information and I've got to go.

inner shuttle
#

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

fallen ridge
#

What am I not seeing? Whenever I press spacebar the gameobject is instantiated but it throws a null reference exception for line 14

pure ore
#

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?

vagrant blade
#

Use GetComponent and call a function on it

modern creek
#

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

pure ore
#

So wait I can access the script that the script is deriving from?

modern creek
#

(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

pure ore
#

I'm using the StandardAssets scripts as a base, just splitting it up into separate scripts

#

The First person controller script

fallen ridge
#

nvm

haughty umbra
cosmic rain
haughty umbra
cosmic rain
#

That doesn't answer my question

inner shuttle
haughty umbra
haughty umbra
cosmic rain
#

*in addition to the video player component

quick relic
#

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

cosmic rain
#

Before you subtract 0.2, it's probably something like 0.20000001 or something like that.

quick relic
#

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

lean sail
# quick relic

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

cosmic rain
rigid island
# quick relic

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

quick relic
#

yeah I'm trying to transfer that to udon graph

broken light
#

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

warm badger
#

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?

spring nacelle
#

How do I make a variable visible but not editable in the inspector?

spring nacelle
#

gross, why must these things not be standard

#

still, thank you

leaden ice
#

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

spring nacelle
#

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

plucky inlet
#

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?

inner shuttle
runic linden
#
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.
warm badger
knotty sun
gray mural
#

Please, show the stack trace

runic linden
#

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)

gray mural
#

It's not about the last line

runic linden
#

The object containing the SceneHandler is a singleton that is in "DontDestroyOnLoad" though, might this cause the issue?

gray mural
#

The exception is thrown when moving IEnumerator

runic linden
gray mural
#

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

runic linden
#

Hold on I was being an idiot

#

Never mind

#

.>

#

Spent 30mins programming and forgot to connect one reference via Editor.

plucky inlet
warm badger
plucky inlet
vital dust
#

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

warm badger
plucky inlet
#

So try it with an empty scene without anything and see if that happens too to track the source of the untracked memory

subtle path
#

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

subtle path
#

no its 2d. and im trying to use rigidbody.addforce

hexed pecan
#

Did you try simply transform.up?

subtle path
#

yes, but that points to the middle of the screen

#

i want it to point in the direction of the bumper

hexed pecan
#

Show your code/what you tried

subtle path
#

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?

hexed pecan
#

Yeah.

hexed pecan
subtle path
#

the code itself is not interesting. its just a gizmo and rigidbody.addforce

hexed pecan
#

Did you perhaps use DrawLine with a position and a direction, while it expects two positions

subtle path
#

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,

subtle path
#

vector.up, vector.zero. I tried to substract the position from the transform.localpos

hexed pecan
#

Use Gizmos.DrawRay instead (takes a pos and dir) or convert your second argument from a dir to a pos

subtle path
#

i tried to use drawray, but couldnt see lines :/

hexed pecan
#

Show what you tried

subtle path
#

Gizmos.DrawRay(transform.position,Vector2.up);

#

i might have used vector3.up before

#

which could be why. now im seeing the line

hexed pecan
hexed pecan
subtle path
#

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

hexed pecan
#

Yes, both work in world space so the direction is the same

subtle path
#

so while the gizmo accepts a from, to vector, the addforce, only accepts one vector

#

it appears to work better now, thanks

hexed pecan
#

There's always AddForceAtPosition if you need

subtle path
subtle path
cold tendon
#

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

plucky inlet
#

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
leaden ice
#

using MonoScript directly instead of UnityEngine.Object will make your code cleaner too btw

plucky inlet
#

Ah never mind, casting as Monoscript was missing, my bad

knotty sun
plucky inlet
#

Now I can grab any script and just call methods , nice 🙂

dusky lake
#

If you for some reason own odin already that is as easy as adding a [Button] tag 😄

plucky inlet
#

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

dusky lake
#

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

plucky inlet
#

Nope, not my issue here. I do not want to call the function from inpsector. Its a UI Button in runtime

dusky lake
#

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

plucky inlet
#

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

raw ocean
#

How do i access the panels rect tranform right stretch?

somber nacelle
gray mural
pearl burrow
#

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)

gray mural
#

So, you'll have it as a serializable class or struct converted to json

thick terrace
gray mural
thick terrace
#

what's the benefit of using JSON there?

gray mural
#

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

thick terrace
#

well, you're the one who said json was better, i don't see a huge difference except json is more work to implement 🤷

gray mural
#

Would you be able to see the difference with a thousand scriptable objects created?

plucky inlet
thick terrace
gray mural
plucky inlet
#

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.

thick terrace
#

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

pearl burrow
gray mural
gray mural
plucky inlet
gray mural
#

Do you want to deserialize all levels at once?

thick terrace
pearl burrow
#

cause i have a List of scriptable object so i can easly go from one level to the next by just increasing the counter

plucky inlet
#

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.

gray mural
pearl burrow
#

and if i want to add another level i just create a new one and add to the list

pearl burrow
gray mural
plucky inlet
white gyro
#

whatever works for your game, be it scriptable object or json, is the "best" solution man

thick terrace
#

yeah it really depends mostly on what workflow you prefer in the editor

pearl burrow
#

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

plucky inlet
pearl burrow
#

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

thick terrace
#

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

untold basin
plucky inlet
pearl burrow
#

correct me if im wrong ofc!

thick terrace
plucky inlet
#

But again, it depends on your whole setup, amount of levels and what not

pearl burrow
untold basin