#archived-code-general

1 messages Β· Page 171 of 1

verbal granite
#

the lag isn't nearly as bad when I'm not running with deep profile, so idk it might be a red herring?

rigid island
#

.velocity = Vector3.zero

grizzled needle
#

hello! I'm running into a bit of an issue when trying to play animations for some models in my project. I'm using the Animation component and pretty much just doing Animation.Stop(); Animation.clip = selectedClip; Animation.Play();
every time i want to do a new animation. This works great generally but I noticed that if I stop an animation in the middle of it, then it'll actually keep it's pose instead of resetting back to how it was at the start... I'm not sure how I can fix this and I'd rather not use an Animator since that just adds a lot more overhead than I need for this thing, but if I have to I'll use one

river wigeon
#

Guys for some reason my auto complete has suddenly stopped working. When I hit enter or tab this happens

#

it just doesn't fill it in

#

It's what happens at the very start of this video

#

on the left

#

I tried to following the steps on there but it's outdated and hasn't helped

#

I think it now uses devtools and not omnisharp?

#

it works when filling in other things like variable names and imports

#

but not functions?

#

idk if I screwed something over by accident? It's just weird

rigid island
#

this is old

#

clickbait title

river wigeon
#

right, so what should I do then?

rigid island
# river wigeon right, so what should I do then?

Microsoft has released a VSCode extension for unity which no longer requires you to go through a a painful process to get code completion , error highlighting and intellisense working.

original guide:
https://code.visualstudio.com/docs/other/unity
Unity for vs code:
https://marketplace.visualstudio.com/items?itemName=visualstudiotoolsforunity.v...

β–Ά Play video
#

its better

river wigeon
#

lol ok I'll check it out

winter fern
#
public class camera : MonoBehaviour
{
    public Transform player_transform;
    public Transform camera_transform;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        camera_transform.position = new Vector2(player_transform.position.x,player_transform.position.y);
    }
}
```why doesn't this work?
swift falcon
#

How can I know that someone is bought a subscribed in my game using the unity in app purchases?

rigid island
#

also don't crosspost

winter fern
#

circle flies away from screen

winter fern
river wigeon
#

still not working unfortunately

rigid island
#

so it's not 2023

river wigeon
#

right

#

I didn't do anything with build tools

#

ignored that part of the vid

#

I'm getting the same issue anyhow

#

it all works except when trying to autofill a function

rigid island
#

mine uses the actual Unity extention microsoft dropped

#

that is part of the new workflow

rigid island
river wigeon
#

there was a pinned comment left in the description of the video saying to install unity and it mentioned about updating the cs extension in the vid

#

anyhow, when I try and autofill this

#

it just doesn't work, or sometimes deletes characters

rigid island
winter fern
river wigeon
rigid island
river wigeon
#

it works for everything like variables and imports but the autofill doesn't work on methods

rigid island
#

or just not at all sometimes

#

if you want a good expeirence use VS Community like everyone else πŸ˜›

#

everyone here highly recommend it

river wigeon
#

this was working yesterday though. It just suddenly stopped working and it doesn't work for any method

rigid island
#

I'd wait till the Unity extension at least goes beyond 1.0

#

it's not even full release yet, expect bugs

#

plenty of bugs

verbal granite
#

Ok I think I fixed the performance problem
I have an Awake() that does

controls.Player.Enable()```
And it seems like when I later do:
```SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);```
It creates a new Controls() every time, and the old ones stick around?
I added
```    private void OnDestroy()
    {
        controls.Player.Disable();
        controls = null;
    }```
and it seems like the problem is gone now.
I'm a little surprised the Controls() don't just get garbage collected though
pure cliff
cursive hollow
#

This is probably a really easy fix that I’m just too stupid to find but it’s saying β€œ(58, 1) error CS1033 type or namespace definition or end of file expected”

#

I have not used unity or C# in like a year so I forget a lot of stuff

somber nacelle
#

configure your !IDE so it points out errors like missing brackets

tawny elkBOT
#
πŸ’‘ IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

β€’ Visual Studio (Installed via Unity Hub)
β€’ Visual Studio (Installed manually)

β€’ VS Code*
β€’ JetBrains Rider
β€’ Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

pure cliff
pure cliff
somber nacelle
#

also line 15 is definitely wrong

grizzled needle
somber nacelle
#

always start with the first error shown in your error list, not the last

pure cliff
spring creek
#

And like 24 is an issue

cursive hollow
#

Ok I fixed the errors but my jump function is acting weird

#

The jumps are very inconsistent with how they act

#

Sometimes it jumps a good height and sometimes it barely moves

random oak
#

any ideas how do I make unity ragdoll land on its feet standing up ?
I know something to do with active ragdoll but how and which rigidbody do I keep up? hips ? legs ? feet?

ebon apex
#

do i ignore this...?

spring creek
#

You'll have to adjust the force after that too

Also, how do you get jump height? Is it changing, because you do a new jumpforce from it every time you jump

lean sail
wintry crescent
#

I can't get visual studio code to work... I keep getting no ability to reference anything outside the current file - no packages, no unity things, nothing

#

I mean in the suggestions bar

lucid valley
#

the while crashed it as it was never going to be false, so was stuck in an endless loop

glass plume
#

no idea why it should never be false, I mean at some point I stop clicking right

#

but I got it

#
if (Input.GetMouseButtonDown(0))
        {
            startPoint = camera.ScreenToWorldPoint(Input.mousePosition);
        }
        if (Input.GetMouseButton(0))
        {
            endPoint = camera.ScreenToWorldPoint(Input.mousePosition);
        }

works

glass plume
#

oh

#

right

#

if I would have done that on a FixedUpdate would that at least not crash?

pure cliff
glass plume
#

i get it like the frame would get stuck so it will never get to call the method again to check if i released the mouse

#

but if its a fixed update and its based on time instead on the frame (like it doesn't matter if that frame is stuck)

pure cliff
#

You almost never need to use while loops, you should avoid them as much as you can unless you 100% for sure know what you are doing, to be completely honest. While loops are the easiest way to lock your game up because you made an assumption about how something works.

glass plume
#

will do

glass plume
pure cliff
#

almost every time you use a while loop, you can just use a for loop instead that has some kind of base case "something went wrong" catch that will fail a bit smoother and not crash unity :x

glass plume
glass plume
#

so if I used the FixedUpdate?

#

still really bad practice but would at least not crash?

pure cliff
#

cant read inputs in fixed update, fixed update is meant for physics/drawing stuff

glass plume
#

but I can read inputs in a fixed update

#

it just runs at different times than the normal update right?

#

Update runs at every frame, unless that frame is stuck and FixedUpdate runs at fixed time jumps?

pure cliff
#

you can accidently "read" inputs twice, or miss them, in fixed update

glass plume
#

yeah

pure cliff
#

but also I believe you'd still get the same infinite loop issue anywho

glass plume
#

oh aight

pure cliff
#

its all running on the same thread still, if you lock that thread, you lock everything

#

cross posting is against the rules, you dont need to cross post, most of the folks who help browse all three channels regularily

glass plume
#

now just a random math question while I am still on this, subtracting two vectors yields the vector in the opposite direction right?
like

powerPoint = startPoint-endPoint

#

something feels very incorrect with that nvm ill go read thank you

fix: i am stupid and its as simple as that

lean sail
glass plume
#

my only problem right now is that ball having a god complex and refusing to collide oh my god i forgot to add a collider

lean sail
# glass plume

If your object was at start, it would go towards -endPoint

glass plume
lean sail
#

Also you dont need fixed update for that, just add force once when launch is supposed to be set true

glass plume
#

i realized having the object be the center or start would be the best idea

lean sail
#

Yea you can fully move that to update

glass plume
#

yeah but you know everyone says physics at FixedUpdate

#

it also helps keep stuff cleaner

lean sail
#

Impulse, velocitychange, and direct changes to velocity dont matter where they are

glass plume
lean sail
#

Because you arent using DT (deltatime) in those forcemode equations, it being in fixed update doesnt matter

lean sail
# glass plume but should I?

It doesnt really make a difference, I'm personally not a fan of running fixed update just to check if launch, when launch could be removed entirely

glass plume
#

nice

simple mountain
#

does somoene know how unity calculates its mesh.recalculate bounds, I tried my own functions but my result is not nearly as good as the normals form unity

quasi pagoda
#

I created a level select screen using buttons, however, I get a null reference exception (object reference is not set to an instance of an object). The level select screen functions fine in the Unity editor but not when playing from a WebGL file. I have not been able to find any tutorials that explain how to avoid null reference exceptions when using buttons.interactable. The null reference exception is flagged at the very first instance in the code where i set EasyYellowButton.interactable = false; (Line 49 of the code here --> https://gdl.space/pupoquraca.cpp) Any suggestions or help would be appreciated. Thanks,

knotty sun
#

So, EasyYellowButton is null

lean sail
#

thats a lot of if statements

quasi pagoda
knotty sun
#

if (EasyYellowButton == null) { }

#

I really think you need some basic programming courses

quasi pagoda
knotty sun
#

Not possible

lean sail
#

after line 77 would imply line 197 or 433, both of which arent in the same function.

quasi pagoda
# knotty sun Not possible

i check if EasyYellowButton is null before line 49 and the debug.log prints that it is null. After line 77 i check for 2 conditions, if EasyYellowButton == null the debug.log will print null (t does not print this) and then i also check if EasyYellowButton != null and it does print the debug.log that says it is not null.

knotty sun
#

post latest code

quasi pagoda
knotty sun
#

That code makes absolutely no sense.
If EasyYellowButton is null then the rest of the code will not execute so there can be no other Debugs

quasi pagoda
knotty sun
#

well learn how to program

quasi pagoda
knotty sun
#

Let me help you a little```cs
if(EasyYellowButton == null)
{
Debug.Log("Line 50: EasyYellowButton is null.");
} else

    EasyYellowButton.interactable = false;
quasi pagoda
knotty sun
#

So this
'i check if EasyYellowButton is null before line 49 and the debug.log prints that it is null. '
is not true?

lone arrow
#

i need help , why the light like the light of a flashlight i dont see in game but in scene i seeΒΏ

quasi pagoda
elfin quest
#

Hello everyone!

I'm working on a MOBA Style game, with point and click movement. Originally, what seemed like a good idea was to use the navMesh and navMeshAgents, but turns out they did not work for me because of the following:

  • I want snappy movement, no acceleration / slowdown on path start or end.
  • For some I don't understand the agets slowed down a lot when making turns (being close to the navMesh zone end).
  • And they would also slow down A LOT when the path of 2 agents intercepeted eachother, and they would act as if a massive velcro strap was between them and take forever to pass eachother. That is, with double-cheked agent dimentions and all that stuff.

What I eneded up with was baking th navMesh, but scraping the agents, and just creating a navMeshPath, take the path corners and have the characters follow the path points until the destination at my complete control of speed, slowdown, path canceling...

My problem now is that even though they respect the navMesh zone they do not care at all about eachother, which is expected they way I've set things up, but I'm running out of ideas on how to implement it.

I've looked into rigydbodies, but they end up going absolutley crazy when reaching the path destination ( whiplash style flying ). Any ideas? Should I ree-add the navMeshAgent, calulate paths through that, but stop them imediatley and still run through the points with my own movement? what should I do?

quasi pagoda
solemn raven
#

hi,
is it possible to search a string for digits or floats or int and replace them with something else ?
for example if string contain x.x ( float) or x ( int) or (x,x,x) (vector3) .... if true>>> replace this part with another string

earnest gazelle
#

Dudes, how do you handle state behaviours on substate machines?
I want it to enter just once when entering that sub state machine which has a state behaviour on as well as for exiting.
It seems OnStateEnter and OnStateExit are called for each state inside a sub state mechine

leaden solstice
cobalt gyro
#
private void Start()
    {
        MyPlayerInput.instance.shootAction.performed += _ => Shoot();
        MyPlayerInput.instance.shootAction.started += _ => Shoot();
        Debug.Log(gameObject.GetInstanceID());
        MyPlayerInput.instance.reloadAction.started += _ => Reload();
    }```
#

for some reason my input isn't using the shoot Action as a hold

#

its being used as a press action

earnest gazelle
#

I want an event to be raised just when entering one of these states and as long as the current state is one of them, it should not raise anything until transitioning into another different state outside the substate

remote eagle
#

it wont let me access it so i can get my text

#

i need it like this

lean sail
remote eagle
#

?

earnest gazelle
#

I have to check the prev state in the state behavior and compare if the prev and the current state behavior have same kinda tag and based on, decide trigger some events.
I have implemented a generic state behavior.

prime copper
#

I'm having some trouble with Simulator, Safe Area, Unity Remote, and UI Toolkit. The simulator seems to be scaling everything up, so when I try to adjust my VisualElement position and size to the Screen.safeArea, it's moving too much/too big. Anyone have any experience with this, and can point me in the right direction?

#

Even if I just adjust the outer VisualElement size to, for example, a width of 2496 (the safe area width for iPhone 12 pro max), in the simulator it ends up being WAY too large (about 4x, it seems).

#

Nevermind, I just found it... it was changing panel setting scale mode to "Constant Pixel Size"

autumn juniper
#

Hello, first time here, I have a question about dictionaries. I understand how to use them in general but how to be specific to game objects I dont quite understand.
In the code I am working on I can spawn a prefab fine, but to remove a game object at a specific key is confusing
This is the code I have been working with, I can remove the index correctly but the object will mot delete properly.
Any ideas?

night harness
dusk apex
autumn juniper
#

I dont have nitro so sending the code is a bit tough @night harness

dusk apex
#

How to post !code

tawny elkBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

vital verge
#

How can I change the parameter in a button event via code? is it even possible

autumn juniper
dusk apex
solemn raven
#

hey?
how to check if Dictinary<string,string> dic 5th item ([5]) has the world "ok" ?

dusk apex
#

With dictionaries, you'd generally have a key and simply acquire the value from the dictionary using said key.

autumn juniper
#

yeah followed it, but they want me to have nitro to send the code anyway

night harness
# tawny elk

If it's too much you just use the sites listed in this bot post

dusk apex
autumn juniper
dusk apex
#

If you've got like.. 5 to 7 lines of code, inline would be okay. Else consider using an external site to link your large code.

night harness
autumn juniper
night harness
#

ah

#

from key 6?

autumn juniper
#

yes

#

excatly

night harness
#

You want TryGetValue

eg

myDict.TryGetValue(myKey, out myValue)
Destroy(myValue.gameObject)
dusk apex
#

I don't think you would want to destroy a prefab..

night harness
dusk apex
#

I'm assuming the dictionary has got instances as values

dusk apex
autumn juniper
#
if (!connectedPlayers.ContainsKey(6))
                {
                    connectedPlayers.TryGetValue(6, out myImage);
                    Destroy(myImage.gameObject);
                    Debug.Log($"connectedPlayers does not contain 6");

                    
                }


#

something like this, but i get a null ref error on destroy

#

woild it need to be in a loop?

night harness
#

Well in this case that code only runs if your dictionary doesn't have a "6" key

#

so myImage will always be null

#

since the trygetvalue fails

#

thats a logic problem you need to solve yourself based on what you want from this but in general you can prevent this by putting the trygetvalue in an if statement since it's a bool

autumn juniper
#

true true

random oak
grave parrot
#

This isn't working and I'm not sure why, https://gdl.space/obedijozit.cpp

Each player is supposed to move with their own keys, but instead they all move at the same time using player 2's keys

quasi pagoda
#

@knotty sun Thanks for your support. It appears that when the code runs the first time, the EasyYellowButton is not null, but when the player clicks on the EasyWhiteButton, a new scene loads and for some reason, EasyYellowButton becomes null. Updated code --> https://gdl.space/amexicizoc.cs

remote eagle
#

when i click on the item it doesnt show the options on the right

#

like this

grave parrot
grave parrot
remote eagle
#

ty

cerulean abyss
#

float minDistance = 0f; // Minimum distance
float maxDistance = 100f; // Maximum distance
float currentDistance = 50f; // Current distance

float minLifetime = 2f; // Minimum lifetime
float maxLifetime = 8f; // Maximum lifetime

// Calculate the interpolation factor based on the current distance
float t = Mathf.InverseLerp(minDistance, maxDistance, currentDistance);

// Use the interpolation factor to calculate the lifetime
float lifetime = Mathf.Lerp(minLifetime, maxLifetime, t);

#

im trying to understand how to use inverselerp to update my position

#

so if the lerp updates the position i need inverse to lerp to change that to set speed which would be like .01 to 1 and i multiply that for what the default speed would be

quartz folio
#

InverseLerp returns a 0->1 value based on how far the third value is between the first and second. That's it, use it for whatever you want

broken light
#

any one seen this error before in unity

#

doesnt seem to be my code but unity specific but i cant press play

quartz folio
#

Have you restarted Unity?

broken light
#

good point will try it now

#

okay that fixed it πŸ˜„

#

thanks

night harness
#

Howdy friends,

Have this code right here:

void Update()
    {
        foreach (DetectableData detectableData in detectableDataList)
        {
            if (detectableData.detectionStateToggle == DetectionState.Increasing)
            {
                if (Physics.Raycast(detectionEyes.transform.position, detectableData.detectable.transform.position - detectionEyes.transform.position, out RaycastHit hit, Mathf.Infinity, detectionMask, QueryTriggerInteraction.Collide))
                    if (hit.transform.CompareTag("Detectable"))
                    {
                        detectableData.detectable.detector = this; //idk about this one
                        TryModifyDetectionRate(detectableData, Mathf.Lerp(detectableData.detectionRate, 100 + (detectionRateMultiplier * 10), DetectionCalculation(detectableData) * Time.deltaTime));
                        if (detectableData.detectable is PlayerDetectable) //this needs to be moved to events
                            detectingAudioUtility.PlayAudio();
                    }
            }
            else if (detectableData.detectionStateToggle == DetectionState.Decreasing)
                TryModifyDetectionRate(detectableData, Mathf.Lerp(detectableData.detectionRate, -100, Mathf.InverseLerp(0, 100, detectableData.detectionRate) * Time.deltaTime));
        }
    }

The problem is that sometimes TryModifyDetectionRate will remove from the detectableDataList which throws an eror since the list was changed during the iteration. The problem problem is that I don't really care that it does this. What's the best way to deal with this error? Should I maybe queue up it's deletion and remove it in lateupdate or something?

broken light
#

oh my lord thats a lot of nested code

night harness
#

it be like that sometimes

broken light
#

it could be a lot cleaner but let me dissect the code to see what the issue is

quartz folio
#

If you can, remove it using an inverse for loop

pure cliff
broken light
#

or do it forward but use a RemoveAtSwapBack function

pure cliff
#

Id also recommend @night harness you look into Guard Clause pattern, it'll help you reduce your nesting there I expect

broken light
#

but you cant remove in a foreach

pure cliff
#

Aside from that @night harness I would instead just have your method return an indicator for if the item should be removed, which you store, then after you finish the iterations, you can perform the removals with any notified "these ones need to be removed"

broken light
#

thats even more messy imo

#

more things to track

pure cliff
#

there's also the option of storing all the items in a Queue, and Dequeue/requeue them

#

and just, neglect to requeue them if you want to "delete" them

broken light
#

thats not necessary just restructure the loop

pure cliff
#

overall though Id prolly completely modify the way you store the data itself so its not in a list, potentially

broken light
#

detectableData.detectable.detector = this; //idk about this one this looks like a signal it needs to be redesigned from the comment alone πŸ˜„

night harness
broken light
#

fair enough lol

night harness
#

thank yall for all the suggestions πŸ‘

#

ended up with kind of a gross solution using a second list, inspired by @pure cliff's suggestion

        if (clearDetectableDataList.Count != 0)
        {
            if (clearDetectableDataList.Count == detectableDataList.Count)
                detectableDataList.Clear();
            else
                foreach (DetectableData detectableData in clearDetectableDataList)
                    detectableDataList.Remove(detectableData);
            clearDetectableDataList.Clear();
        }  
pure cliff
#

Also, its good practice to scope your if statements even if 1 liners

#

Saving a couple braces is typically not worth making your code much harder to read and potentially introducing lots of bugs down the road D:

night harness
#

your right but im stubborn πŸ˜„

pure cliff
#

Also you can do a guard clause at the top

#

anytime you have

if (condition)
{
   logic
}

You can just invert it to be

if (!condition)
{
    return/continue/break
}
logic

which reduces a layer of nesting in logic

night harness
#

What's the benefit?

pure cliff
#

reducing nesting

#

which makes your code a lot easier to read and maintain

#

if you have this:

if (conditionA) {
    if (conditionB) {
        if (conditionC) {
            ...
        }
    }
}

Your logic becomes a lot harder to keep track of

night harness
#

i see

pure cliff
#

Versus:

if (!conditionA) {
    return;
}
if (!conditionB) {
    return;
}
if (!conditionC) {
    return;
}
...
#

You'll quickly also notice that if there's some kind of typo in your conditions, they are all nice and neatly lined up single file vertically and a typo suddenly sticks out like a sort thumb πŸ™‚

night harness
#

I will keep this in mind, Thanks

broken light
#

i would also move each logic to a function too

nova magnet
spring creek
#

I would debug the line after setting held

spring creek
#

you cast AmmoMaster (which you called type) as an int, to get the index

lean sail
#

can you show the AmmoMaster class?

spring creek
#

Maybe show the AmmoMaster script?

#

oof, too slow

nova magnet
#

wait

#

`using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public enum AmmoMaster: int
{
Magnum,
AR,
Buckshot,
Rockets
}`

AmmoMaster in all of its glory

lean sail
#

ah shouldve realized its just an enum

spring creek
#

Ah, ok. You don't have to inherit from int by the way

nova magnet
#

in GunInv

lean sail
#

should be fine to just remove, but I really wouldnt rely on casting enums to ints in this case. If you add or change the enum ever, all ammo types will be wrong

spring creek
#

I mean, you can already cast enum directly as int. I would remove that " : int" part

nova magnet
#

error CS1031: Type expected

spring creek
#

You can hard-code the enums like this:

Magnum = 1,
AR = 2

To slightly make what bawsi said less of an issue

And where is that error?

nova magnet
#

(erased the int)

spring creek
#

from the AmmoMaster class, or the _inventory[(int)type] line?

nova magnet
#

Assets\Player\Weapons\AmmoMaster.cs(5,24): error CS1031: Type expected
aka public enum AmmoMaster: int

spring creek
#

Well you have to get rid of the : as well

nova magnet
spring creek
#

But yeah, put some debugs in the code here #archived-code-general message

Check the amount, check held after it's set, and check spend after you run min on it

dense tusk
#

i come with a question. i'm trying to save a copy of a list into a variable, but i'm having trouble getting that to work.
dialogueScript.stringList = selectedObject.GetComponentInChildren<DialogueInfo>().dialogueOptions;

now this works, but when i clear stringList in another script, it also clears the original list, and i can no longer access it. i reckon i just need to do something like new List<string> but i'm not sure how to properly format it so i can reference dialogueOptions
what would be the proper way to do that?

(full disclosure, i did originally ask this in #πŸ’»β”ƒcode-beginner but that channel was a little busy with other topics, so i thought it better to delete it and move it here. if that was incorrect, i apologize and won't do it again)

lean sail
spring creek
dense tusk
#

lmao nice edit

spring creek
nova magnet
#

thats why its commented out

dense tusk
spring creek
lean sail
spring creek
#

The issue is the amount?

nova magnet
#

Assets\Player\Weapons\GunCore.cs(82,17): error CS7036: There is no argument given that corresponds to the required formal parameter 'ammo' of 'GunCore.Fire(AmmoInv)'

spring creek
#

You just have Fire()

#

That won't work

#

because you need to pass in ainv

#

Fire(ainv)

nova magnet
#

oh

spring creek
#

If a method takes a parameter, you have to give that parameter when you call the method

dense tusk
nova magnet
#
    public struct AmmoEntry
    {
        // Include name field for editing convenience only - not needed in-game.
#if UNITY_EDITOR
        [HideInInspector]
        public string name;
#endif
        public int maxCapacity;
        public int stock;
        [SerializeField] public int magazine;
        [SerializeField] public int maxMagazine;
        //ddd
    } ```
why cant magazine be detected?
cosmic rain
#

wdym by "detected"?

nova magnet
#

if (ainv.magazine > 0) == error CS1061: 'AmmoInv' does not contain a definition for 'magazine' and no accessible extension method 'magazine' accepting a first argument of type 'AmmoInv' could be found (are you missing a using directive or an assembly reference?)

#

i changed it to if (ainv.AmmoEntry.magazine > 0) now error CS0120: An object reference is required for the non-static field, method, or property 'AmmoInv.AmmoEntry.magazine'
and
error CS0572: 'AmmoEntry': cannot reference a type through an expression; try 'AmmoInv.AmmoEntry' instead

#

if i use AmmoInv.AmmoEntry, error CS1061 remains

cosmic rain
#

Does your AmmoInv type have an AmmoEntry property/field?

cosmic rain
lean sail
#

you may want to try basic c# courses first. AmmoEntry is a struct, so ainv.AmmoEntry really doesnt make sense.
Your ainv is a AmmoInv

cosmic rain
#

No, it doesn't have it.

#

It has a definition of the AmmoEntry struct. It doesn't have a property or field of that type.

nova magnet
spring creek
# nova magnet yes
[System.Serializable]
public struct AmmoEntry
{
    // Include name field for editing convenience only - not needed in-game.
#if UNITY_EDITOR
    [HideInInspector]
    public string name;
#endif
    public int maxCapacity;
    public int stock;
}

Where is the struct you posted above, because this is in that code you just linked

#

It simply doesn't have magazine

cosmic rain
dusk apex
dusk apex
#
public struct Example 
{
    public int a;
}
public Example ex;``````cs
myClass.ex.a = 5;```
spring creek
#

You should take this course. Between this and not knowing how to add a parameter to a method, it's clear you need to understand the foundations a bit better
https://www.w3schools.com/cs/index.php

dusk apex
#

Not cs myClass.Example.a = 5;//Error!

cunning meteor
#

can i ask a visual studio question

thin aurora
cunning meteor
#

i need help with downloading a certain colsole app

#

in visual

thin aurora
#

Did you read the big header that mentions this channel is for general coding concepts in unity? πŸ˜„

#

You should ask those questions here πŸ‘‡ , considering it's in no way related to Unity

tawny elkBOT
pine bronze
#

hey guys, i've made an asset menu, and all of the fields show up in the inspector, except one, its public, so idk why it doesn't show up. this is the code for the asset menu https://sourceb.in/G2bjvjjEKv
(there should be a noiseSettings field)

lean sail
pine bronze
#

thanks!

thin aurora
#

Unity's dumb BinarySerializer strikes again

scarlet viper
#

how to stop JSON UTILITY from making vector3s look like this

#

im already rounding the value before

#

my correction it probably makes all floats look like this

dusk apex
lean sail
#

possibly
store as rounded string then convert on load
round it when you read it
use newtonsoft

scarlet viper
thin aurora
#

It's trash

#

You can migrate to newtonsoft very easily and it will work a million times better

scarlet viper
#

i see

thin aurora
#

Only the Vector3 and other math related types will not work properly because Unity has not put any effort into supporting it, but you can add a custom type converter that fixes this

#

If you are going to migrate, then I can look for a solution if you want, or just write one myself

scarlet viper
#

no need i can find it on my own thanks

thin aurora
#

Right

#

Either way, you can't fix your issue as far as I know. This is JSON Utility serializing your Vector3

#

Right now we can't help you because we have no idea what you actually tried code wise

cinder wigeon
#

Hello
I am having troubling with serialization on different platforms. The object I am serializing is basic (shown below). I am serializing it with JsonConvert.SerializeObject.
In the editor, this works prefectly. But on Android and WebGL, the serialization results in an empty object {}.
I am using Unity 2020.2.3f1.

Additionally, I tried attaching the visual studio debugger and inspecting the object. It worked as expected in the editor. But on android, it says "children could not be evaluated".

    [Serializable]
    public class Log : BaseRequest
    {
        [JsonProperty]
        public long time { get; private set; }
        [JsonProperty]
        public string token { get; private set; }
        [JsonProperty]
        public string type { get; private set; }
        [JsonProperty]
        public string data { get; private set; }

        public Log(IUser user, string type, string data) {
            this.time = DeploymentEnvironment.UnixTime;
            this.token = user.Token;
            this.type = type;
            this.data = data;
        }

        [JsonConstructor]
        public Log(long time, string token, string type, string data) {
            this.time = time;
            this.token = token;
            this.type = type;
            this.data = data;
        }
    }
thin aurora
#

Very confused because it does not look like JSONUtility but Newtosoft does not throw silent errors like that

#

So you must have an error

grave parrot
#

I want to make an item go around the player and point towards the cursor, what would the best way to do that be

cinder wigeon
#

using Newtonsoft

elder zenith
#

I'm losing my fucking mind.

https://hatebin.com/fklyqrltaa

Here's my code. I've put the Gnome script on a completely fresh new empty object.

I spawned a default 3d cube right above it.

It does not detect a hit, ever. I can put the cube above, i can put the cube right on the empty, it does nothing.

But for some reason, when I switch the cube's collider to trigger, it suddenly catches it (this was sometimes the case even without the QueryTriggerInteraction.Collide), but even if i switch the trigger back off, or move the cube away, it still continues outputing "HIT" to the console and RaycastHit still returns the cube.

#

just checked another thing and it seems to fix itself whenever i put 2 colliders in its path?????

cinder wigeon
lean sail
elder zenith
#

There's nothing to step through, the Physics.Raycast just does not hit.

Yes, I switched the layermask to -1, just in case that was the cause of the problem

lean sail
fervent furnace
#

-1 is 0xFFFFFFFF=enable all layers....

lean sail
#

Ah true

elder zenith
#

It seems to bug out whenever I start the scene.

Started the scene, moved the cube over the raycast - nothing. Turned off the collider, turned it on - now it works. Feels like something isn't updated properly on the Physics end

lean sail
#

Have you ever changed any of the physics settings?

elder zenith
#

Nope, never. Unless my colleague did, but dont think they would

cosmic rain
elder zenith
#

It's fixed now, I think it might've been the fact that i was using Update instead of FixedUpdate

cosmic rain
#

Hmm

tawdry jasper
#

I have a problem with not all UnityEvent hooked up callbacks get called, when I call event.Invoke(); The first one always does, but I now have multiple callbacks (on the same gameobject, but different monobehaviours) the second one gets called pretty much on every other run. Is there a common reason for a callback to be ignored?

cosmic rain
scarlet viper
#

nvm i had to turn on readwrite

tawdry jasper
#

@waxen phoenix I can see one difference between your code and mine: you don't set subMeshIndex on your combined instances.

scarlet viper
#

it works now but thanks ill check it

tawdry jasper
#

@waxen phoenix I don't know if it's important to you, I'm combining meshes from an asset that shares materials among models so I group them so the combined submeshes use the same materials.

scarlet viper
#

no i have my own material

#

specifically for it

steady moat
tawdry jasper
#

No errors in the console. I ended up adding the second callback as a DOTween callback, so I only have one handler on my unityevent, cause I do have deadlines on this... but next time I need 2 callbacks I'm going to try to debug what exactly is going wrong.

versed patrol
#

Inventory System as ScriptableObjects? What if I have hundreds of NPCs with all of them having 10+ items? Makes sense to keep using SOs?

steady moat
#

Think of SO as immutable data.

versed patrol
#

So should I just use Serializable base class?

steady moat
#

Yes.

versed patrol
#

alright that's what i was doing

steady moat
#

The item can be SO though. (The part that is immutable like name, description, icon)

versed patrol
#

alright

#

what if i have changeable values like durability that inherit the SO item class?

steady moat
#

You have a SO that is the concept of the item. (Name, Description, Max Durability, Strength, Agility, etc.)
You also have a class that represent the current item. (Durability, IsEquipped, etc)

versed patrol
#

so I'm guessing the current item HAS an SO attached instead of inheriting it?

quartz folio
knotty ruin
tawny elkBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

knotty ruin
#

oh sory

heavy wren
# knotty ruin someone can tell why I always spawn uder world (sory for my bad english) https:/...

The Player transform is spawning underneath the terrain? Or does it have a child object that is translated lower and only looks like it spawned lower than the terrain height? Also, you rewrite the height formula twice, but it's very intricate, so I would recommend creating a method for it:

float GetHeight(float x) => Mathf.PerlinNoise((x + seed) * terrainFreq, seed * terrainFreq) * heightMultiplier + heightAddition;
knotty ruin
#

thanks

stone scaffold
#

Hello,
I'm making a 2D game and attempting to have an enemy follow me however it flies through the air instead of sticking to the ground when following. Is there a way I can keep it on the ground without using Raycasts or is Raycasting the only option?

leaden ice
#

In general there are many ways to solve any given problem. I would probably have a physics-based character controller for the enemy and a separate AI script to drive it.

rocky helm
#

Does anyone know what could cause rigidbodies to not move after doing rigidbody.position = ...? The rigidbody is on RigidbodyInterpolation.Extrapolate and CollisionDetectionMode.ContinuousSpeculative and also kinematic. I know, I know, this is probably not much to go off of, but I haven't been able to gather much more info myself either since it seems to be happening very rarely, most likely because update and fixedupdate have to be called in a specific order for this to occur. Basically I want to know if anyone has had or knows possible problems that could be the case for me. If I manage to get it to happen whilst debugging and get some more important information I'll let you know.

swift falcon
#

Can anyone explain why this is happening with my third person RB controller?

rocky helm
swift falcon
#

Already tried that...

rocky helm
tawny elkBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

swift falcon
stoic blade
#

Hi all I am getting a mismatch error after I instantiate the sectorGameObject sector is the scriptable object I have a prefab gameobject in.

#

can anyone help please?

rocky helm
stoic blade
#

nope no error in the inspector just my scriptable object. ill show you before and after

stoic blade
#

before and after

#

everytime i restart the game i have to re-assign the gameobject in the scriptable object

swift falcon
leaden ice
# stoic blade

Assets cannot reference objects in scenes at edit time

#

that reference is only going to be valid at playtime / until a domain reload

stoic blade
#

ok but i should not have to keep re-poplating my scriptable objects everytime time cause when i stop to restart i then get a null ref error because the object has now been removed.

#

when I am instantiating from the scriptable object something is causing to be removed from the scriptable object. this is what I am trying to fix.

leaden ice
#

it is not possible for assets such as prefabs and SOs to reference scene objects except at runtime

sweet yoke
#

What could be the reason my parent Gameobject change values for transform position in the start of the game ? As result my level is asynchron.

Image1: parent
Image2: chield
Image3: parent while play

This issue does not occur if there is no child.

leaden ice
whole gull
#

When I have a ScriptableObject with an "AudioSource" property, it is not possible to drag an drop an object from a prefab inside this property in the inspector.
Is this generally not something you'd want to do anyway or is there a way to achieve this.

leaden ice
#

from the scen you can't

swift falcon
#

I got an Abstract class that has 3 or actually more functions which is some of them private, some of them public. I will use that same Abstract class's methods for Monobehaviour either ScriptableObject. But i couldnt solve it since it accepts only one base class. Example:

`public abstract class X: ScriptableObject
{
public abstract IEnumerator MethodIEnumRequired();
private protected abstract void MethodPrivateRequired();
public abstract void MethodPublicRequired();
}

// Fine for ScriptableObject's
public class AScriptableObject : X {

}

// Error here. Cant define multiple Base class
public class AMonoBehaviour : MonoBehaviour, X {

}`

I dont want to define second abstract class or it is my actually last chance. I need only one Base class. I was trying to solve this like tomorrow but my knowledge is not enough or maybe it is not possible.
I cant use Interface's or maybe i can i dont know.
Class X will have some shared Private/Public Fields too.

Its indeed impossible. We need two seperate abstract class for each and one Interface to keep Public methods required.

scarlet viper
#

How to overlap check with mesh colliders ? (the dumbed down ones)

shut elm
#

Hi, I made a big complex change to my Game (added a entire new System), now I noticed, that everything is pretty laggie. I have around 40 fps right now, which was around 90 to 120 before. Is there a way to chace down the issue of the performance issues? Like, is there a way to see which code / script is the cause of the perfomance issue?

whole gull
#

I double click the prefab, and drag the object which has the audiosource as the component on top of the audisource property from the scriptable object

shut elm
#

but as far as I see there is not exact list of which script takes how to long to be executed. Is there a way to display the data like that?

sweet yoke
#

why cant i use velocity on a rigidbody kinematic while its working fine on rigidbody2d kinematic ? Does exist any workaround ?

heavy wren
leaden ice
#

so it's unclear what you're actually trying here

whole gull
#

I think what I'm trying doesn't make sense

#

it doesn't make sense to reference a component of something that only exists during runtime in a scriptable object, only things that exists before

#

correct?

whole gull
#

yeah, ok, I'm still trying to understand SOs, currently switching a lot of things over and really enjoying working with them

#

thanks

shut elm
#

ohh, thank you

heavy wren
shut elm
#

thx, already got it. The issue was that the code somehow executed the part of the worldgeneration two times (so every gameobject was placed two times)

sweet yoke
vivid raven
#

i have a randomized spawner that Instantiates another spawner that Instantiates a coin, when the coin is collected it calls a function that spawns another coin, the function is in the spawner that Instantiates coins, when i run the game the coins only get Instantiate in the original coin spawner, but is it possible to call the clone of the coin spawner? diagram to expaline it better

modern creek
# vivid raven i have a randomized spawner that Instantiates another spawner that Instantiates ...

this is some next level inception design... but, yes, you can. Give your spawner a method (i usually name mine Initialize()) and pass a reference to the original, and track that reference.. ie:

public class OgSpawner : MonoBehaviour
{
  public void SpawnRandomNewSpawner()
  {
    NewSpawner ns = Instantiate(...);
    ns.Initialize(this);
  }
  public void DoSomethingLater() { ... }
}

public class NewSpawner : MonoBehaviour
{
  private OgSpawner _originalSpawner;
  public void Initialize(OgSpawner originalSpawner) => _originalSpawner = originalSpawner;

  public void OnCoinCollected()
  {
    _originalSpawner.DoSomethingLater();
  }
}
vivid raven
indigo arrow
#

I have a chest object that appears in every room of the map where, once the player touches its trigger, it enables two buttons and sets these buttons to different cards. The player can choose one of the two cards to keep and the other gets discarded. The issue I have is, how do I get the buttons to always reference the current room's chest on it's OnClick() method?

using System.Collections.Generic;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityEngine;

public class CollectCard : MonoBehaviour
{
    public AudioClip cardCollectAudio;
    AudioSource source;
    public List<CardEffect> lightCardPool = new List<CardEffect>();
    public List<CardEffect> darkCardPool = new List<CardEffect>();
    public CardEffect thisLightCard, thisDarkCard;
    public Button lightButton, darkButton;
    GameObject player;
    
    void Start()
    {
        source = GameObject.FindWithTag("GameManager").GetComponent<AudioSource>();
        player = GameObject.FindWithTag("Player");
        thisLightCard = lightCardPool[Random.Range(0, lightCardPool.Count)];
        thisDarkCard = darkCardPool[Random.Range(0, darkCardPool.Count)];
        lightButton = GameObject.Find("Canvas/Cards/LightCard").GetComponent<Button>();
        darkButton = GameObject.Find("Canvas/Cards/DarkCard").GetComponent<Button>();
    }

    void OnTriggerEnter2D(Collider2D col)
    {
        if(col.gameObject.CompareTag("Player"))
        {
            SetupChoice();
        }
    }

    void SetupChoice()
    {
        lightButton.transform.parent.gameObject.SetActive(true);
    }

    public void OnCardChose(CardEffect chosenCard)
    {
        lightButton.transform.parent.gameObject.SetActive(false);
        source.PlayOneShot(cardCollectAudio);
        chosenCard.ApplyEffect(player);
        Destroy(gameObject);
    }
}
nimble echo
#

Why isn't OnTriggerEnter2D() working on the "shot" prefab(collider and rigidbody attached in 1st pic)? I've made fully sure it's colliding with the object(collider and rigidbody attached in 2nd pic) but still it's not working. I've searched a lot but found no solutions.

modern creek
manic maple
#

What's lerping in unity?

indigo arrow
#

that

modern creek
#

you can pass a parameter (which is a little sloppy in my opinion, but many people do it this way)

modern creek
#

try adding (int parameter) to OnCardChoseRelay()

#

better is probably setting whatever type of card is when you instantiate it, so the button "already knows" what type it is and just.. adds the correct card or whatever to the deck

rigid island
indigo arrow
#

But i dont understand how i set that variable

modern creek
#

After you instantiate the card, set it with an initialize (or whatever you want to call it) method

#
public void OnPlayerOpenedChest()
{
  CardEffect left = Instantiate(CardEffectPrefab);
  left.SetCardType( /* random type for left card */ );
  CardEffect right = Instantiate(CardEffectPrefab);
  right.SetCardType( /* random type for right card */ );
}

public class CardEffect
{
  private CardEffectType _type;
  public void SetCardType(CardEffectType type) => _type = type;
  public void OnClicked()
  {
    // add _type to the player's deck/collection
  }
}
indigo arrow
#

would this work as a substitute

    {
        lightButton.transform.parent.gameObject.SetActive(true);

        lightButton.onClick.RemoveAllListeners();
        lightButton.onClick.AddListener(() => OnCardChose(thisLightCard));
    }```
#

something like that

modern creek
#

sure

indigo arrow
#

alr thanks

indigo arrow
# modern creek sure

how would I get a reference to the buttons if they are inactive when the Start() function of the chest is called?

#

as I can't use the transform.Find("") function

modern creek
#

Are you Instantiate()-ing them? Or do they already exist in your scene

indigo arrow
#

they already exist

#

but are inactive when I am trying to refernce them

modern creek
#

If you're using Instantiate() to create a new button, then keep a reference to it:

CardEffect newCardEffect = Instantiate(CardEffectPrefab, ...);
// now do something with newCardEffect - call a method on it that tells it what kind of button it is, for example:
newCardEffect.Initialize(CardEffectPoison); 

If you have them in your scene, then create a script and variables to track them:

public class CardScene : MonoBehaviour
{
  public CardEffect leftButton;
  public CardEffect rightButton;
}

and do the same - initialize them when you "create" them (or show them)

#

you can still reference items that are inactive

indigo arrow
modern creek
#

the descriptions i just gave you make it so you don't need Find

#

which you shouldn't be using anyway

indigo arrow
modern creek
#

because it's [very] slow, and you should learn how to track references to things anyway.. if you fill up your game with Find() you're gonna find (ha) pretty soon your game's performance is terrible

#

doing it once or twice is fine, but realize that in order for find to work, it has to traverse the entire object tree - literally every single object and component in your game

modern creek
#

i mean, sure, but I don't really understand why you aren't just doing it yourself - you already know the reference to the object, you don't have to find it

#

for some reason you're selecting to do it in a way that's neither simpler nor better πŸ˜›

indigo arrow
#

Because the chest and its parent are prefabs

modern creek
#

so?

indigo arrow
#

So i gotta reference it in the chest

#

because a prefab can't retain a non-prefab variable

modern creek
#

yes...... and I've posted how you do it like.. 3 times πŸ™‚ Show me the code and I'll literally write it out

modern creek
indigo arrow
modern creek
#

sigh

#

Yes, it absolutely can, you just need to do it - like I've described above a bunch of times. πŸ™‚ Show me the code for your prefabs

indigo arrow
#
using System.Collections.Generic;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityEngine;

public class CollectCard : MonoBehaviour
{
    public AudioClip cardCollectAudio;
    AudioSource source;
    public List<CardEffect> lightCardPool = new List<CardEffect>();
    public List<CardEffect> darkCardPool = new List<CardEffect>();
    public CardEffect thisLightCard, thisDarkCard;
    GameObject cardsParent;
    public Button lightButton, darkButton;
    GameObject player;
    GameObject gameManager;
    
    void Start()
    {
        gameManager = GameObject.FindWithTag("GameManager");
        source = gameManager.GetComponent<AudioSource>();

        player = GameObject.FindWithTag("Player");

        thisLightCard = lightCardPool[Random.Range(0, lightCardPool.Count)];
        thisDarkCard = darkCardPool[Random.Range(0, darkCardPool.Count)];

        lightButton = gameManager.GetComponent<RoomManager>().lightButton;
        darkButton = gameManager.GetComponent<RoomManager>().darkButton;
        cardsParent = lightButton.transform.parent.gameObject;
    }

    void OnTriggerEnter2D(Collider2D col)
    {
        if(col.gameObject.CompareTag("Player"))
        {
            SetupChoice();
        }
    }

    void SetupChoice()
    {
        cardsParent.SetActive(true);

        lightButton.onClick.RemoveAllListeners();
        lightButton.onClick.AddListener(() => OnCardChose(thisLightCard));

        darkButton.onClick.RemoveAllListeners();
        darkButton.onClick.AddListener(() => OnCardChose(thisDarkCard));
    }

    public void OnCardChose(CardEffect chosenCard)
    {
        source.PlayOneShot(cardCollectAudio);
        chosenCard.ApplyEffect(player);

        lightButton.transform.parent.gameObject.SetActive(false);
        Destroy(gameObject);
    }
}
#

this is the current code I have written

#

havent tested yet

#

the gameManager stores the buttons and the chest finds it and gets the variables as references.

modern creek
#

and what's this for? one instance of a "collect card"? ie, when you have a chest, there are two of these that pop up?

indigo arrow
#

Yes

#

I believe so

#

When you collide with the trigger, two buttons are enabled and you choose one of the two

modern creek
#

I'm confused - is this a "chest" (ie, is there one of these?)

#

and there's 2 CardEffects?

indigo arrow
#

Yes

#

the CardEffects are, in essence, stat boosts

wintry crescent
#

Hi, I've done the setup in #854851968446365696 , but my vscode still doesn't give me suggestions for things from outside of the current file - how can I fix it? I'm on linux, endevourOS

modern creek
wintry crescent
indigo arrow
modern creek
#

@indigo arrow show me CardEffect.cs

#

how are you rendering the card effect buttons? is it just literally a Button?

indigo arrow
modern creek
#

fine, and so what's the problem again? pressing the button has no effect?

thick socket
#

what all should I have broken off into other files in yalls opinion...this is my Loadout Managers functions and its over 1000lines :/

#

Im thinking the popup ones should have been in other file

#

not sure what all else

modern creek
#

You have a mess of code here - popups should take care of themselves, items should take care of themselves, navigation should all be in the same place, etc

indigo arrow
#

It works perfectly fine now

#

the issue was that at first, I didn't know how to add a listener

thick socket
#

so items shouldn't do that part imo?

indigo arrow
#

and after that, I didn't know how I would reference an inactive button

modern creek
#

What's a "Loadout"? Like, which items are equipped in which slots?

thick socket
#

LoadoutManager is basically in charge or everything you see here

#

items, buttons, equiping items things like that

modern creek
#

So like, you have tonnnnnnns of logic crammed in here. Your mental model of what a component is should be smaller - typically (well, for me anyway) you only orchestrate conversations between components at the smallest possible level

#

So like, your items in your inventory - these should be something like ItemRenderer or ItemIcon that has all the logic for what item to draw, what the text is, what the rarity color is, etc

#

it should also be able to handle it's own drag & drop - if you need to orchestrate it at the parent, you implement the mouse down/up/click/drag at in the icon component, then have the parent orchestrate.. am I making sense? lemme maybe stub out some code

thick socket
thick socket
#

(I at least broke the hero info/her upgrades into another file...which is also like 500lines now lol)

modern creek
#
public class ItemIcon : MonoBehaviour, IPointerDownHandler, IPointerDragHandler, ... etc
{
  private LoadoutScreen _loadoutScreen;
  public void Initialize(LoadoutScreen loadoutScreen) => _loadoutScreen = loadoutScreen; // and whatever info you need to render an item
  public void OnDragEndHandler(...)
  {
    _loadoutScreen.ItemDropped(eventArgs.position);
  }
}

public class LoadoutScreen : MonoBehaviour
{
  public InventoryPanel inventoryPanel;
  public LoadoutPanel loadoutPanel;
  
  public void InitializeInventory()
  {
    foreach (GameItem item in Player.Inventory.Items)
    {
        ItemIcon itemIcon = Instantiate(ItemIconPrefab, InventoryContainer.transform);
        itemIcon.Initialize(this);
    }
  }
  
  public void ItemDropped(Vector2 position) // and item type, or whatever
  {
      // check if it's on the loadout, if it's a valid item, etc, if so, remove it from inventory and add it to the loadout
  }
}
#

something like that - LoadoutScreen only handles orchestration between the panels, but the panels/icons render themselves and have all the logic related to .. just the smallest piece of UI you possibly can

thick socket
modern creek
#

the ItemIcon in my example above tells the "parent" (LoadoutScreen, in this example) that it's been dropped on some location. LoadoutScreen tells the "LoadoutPanel" that it's been dropped, maybe it has some logic to check if it's a valid drop, and if not, tell the icon to "go back to the start drag location")

thick socket
#

gotcha...do they all need to be in their own file? or just own class

modern creek
#

in my bigger project, my "renderers" are quite numerous

#

I'd put them in their own class and even nest them by functional area

#

but this makes the design of your app simple - if you need a draggable icon of some sort (like, in your inventory, loadout, maybe in a chest popup dialog showing what's in the chest, maybe on the store page, etc) you only need to write that script and code once

#

and every place that "holds" it just says "ok create an icon of type Iron Chest Armor" and away you go

thick socket
#

do you like "write out" what each code should have and how many files to create beforehand?

#

or do you kind of just jump into coding πŸ˜„

modern creek
#

i've been doing it long enough that i just sorta know what needs to be created, and I have my own library of stuff that i reuse

#

but in general, the smaller your "thing" is, the better

#

like, for example, in our game we have resource icons - gems, credits, green gel, and "aurite".. i have a resource icon that I can use eevvvvvvvvvverywhere without needing to write logic to show 1 of 4 images based on the type

#

it's really a simple "renderer":

#

but anyplace I need one of these, i just instantiate one and call Initialize(ResourceType) on it and it draws itself

#

Another small example but more "pure" - I use sliders everywhere in my games, and wanted to make a few features on them that the default unity sliders don't have - a gradient for texture color and text color, and animation.. so .. I have a class that does all these, and I can just add this prefab to any other object that has a slider and it "just works" without needing any scripting.

Also I hated always writing slider.value = (float)currentValueInt / maxValueInt; so I also just wrote that line of code once in my slider with a different API: slider.SetPercent(currentValueInt, maxValueInt) which does things like always convert it to a float, clamp it to 0-1, etc.

#

So as you go in your game dev, you just build your own library of components (reusable or otherwise) so your source code is small and you don't end up with 1000 line files

craggy veldt
#

Nothing wrong for having 1000 lines of code πŸ˜„

leaden ice
#

your code

cerulean abyss
lean sail
modern creek
#

8000 lines in 1 file...... πŸ‘€

#

If you were on my team you'd have a "do this right now" task related to that.. πŸ™‚

pure cliff
modern creek
#

perhaps not πŸ˜›

pure cliff
#

Ive seen some pretty nasty big stuff generated by automated mechanisms that have no qualms about just casually plunking a several ten thousand line long balrog into the source o_O

#

but we dont check that into git since it generates on compile wheeee

modern creek
#

Yeah, unfortunately mine has to be in git because we build from git and android needs AOT

indigo arrow
#

How would I overried an abstract sprite:

{
    public abstract Sprite cardSprite {get; set;}
    public abstract void ApplyEffect(GameObject target);
}```
With another sprite in a subclass:
```[CreateAssetMenu(menuName = "Powerups/Damage")]
public class DamageCard : CardEffect
{
    public float damageMultiplier;
    public Sprite damageSprite;

    public override void ApplyEffect(GameObject target)
    {
        target.GetComponent<PlayerShooting>().bulletDamage *= damageMultiplier;
    }
}```
And then be able to access it in another script:
```Sprite thisCardSprite = chosenCard.cardSprite```
wintry crescent
#

Does anyone know why vscode might still not show code suggestions, after doing all the setup in #854851968446365696 ?

#

I write Time. and it doesn't suggest anything like deltatime
I write GameO and it doesn't suggest GameObject

#

it only shows suggestions from System libraries

pure cliff
#
public override Sprite { ... }
indigo arrow
#

but what is the syntax

#

like what do i set and get

pure cliff
# indigo arrow but what is the syntax

theres a good three different ways to declare properties, but its the same as usual for a property, you just have to put override in its declaration, like what I wrote above

#

usually having set; exposed on an abstract property is a bit of a code smell though, if its abstract typically its get; only unless you are doing some fancy stuff with the getter/setter on purpose

indigo arrow
pure cliff
#

can just put this on the parent class and call it a day

[SerializeField] private VarType _myVariable;
public VarType MyVariable => _myVariable;

What whatever you drag and drop onto _myVariable in the inspector will be exposed (readonly) through the property (but cant be set, only get)

wintry crescent
wintry crescent
#

it won't work then

pure cliff
#

I would, when using an abstract base class, go with the assumption that there may be need for a fancy implementation downstream, so I'd even go so far as to declare it as public virtual to enable overriding capability.

#

otherwise it can be a bit of a pain to undo the above and convert it over if you've tightly bound your stuff together, and renaming/changing the field/prop can even deref the stuff in the inspector so now you gotta go and do a bunch of drag and drops again D:

wide dock
#

I need some help with this... I've been trying to fix it for a while now but I have no idea what might be the issue.

I basically have a worm enemy with several body segments and a tail, which are supposed to follow the head, so I save the head's last position and rotation in a queue and then just update the worm segments to the head's previous positions & rotations (the head's movement itself takes place in a coroutine, so probably somewhere between Update and LateUpdate)

For some reason if you focus well enough you can notice some weird "snapping" going on with the body segments, as if they lagged behind and shortly after snapped back into place. Usually it's negligible, but sometimes this snapping if fairly visible and I don't know how to stop it

#

(It's mostly visible here when the worm is moving on top, from left to right, after the first loop - after 0:06)

vale creek
#

I haven't been able to find anything online, in beginner, general, or the input system. I'm trying to get local coop to work with 2 xbox controllers specifically. I have each controller moving their respective player but only one controller is able to send input at a time. So if I hold fire on both controllers only the one that was pressed first will work. Any idea of there's a setting or something that needs to be done to be able to accept the input from both controllers simultaneously?

leaden ice
vale creek
#

not quite

wintry crescent
#

Does anyone know if SphereCastAll returns results sorted by distance? Or just randomly

#

unity docs don't seem to have an answer

#

nevermind, the SphereCastNonAlloc does have an answer, it's random

nocturne grove
#

Anyone happen to know a way to get the normals of two connected line segments on a polygon collider 2D, or even a way to get the normal at corners?

lean sail
leaden ice
quartz glen
#

Hello does someone know how to code this effect for an int or a float ?

leaden ice
#
float targetValue;
float displayedValue;

void Update() {
  displayedValue = Mathf.MoveTowards(displayedValue, targetValue, Time.deltaTime * speed);
}```
quartz glen
#

For example with a health bar the displayed value is before damages et the target value is after damages ?

leaden ice
#

target value is the "actual" value

quartz glen
#

Okay thank you i will try it

#

I thought it was more difficult to do that

topaz ocean
#

How could I go about using ComputePenetration to get a trigger to behave like a non-trigger collider?

Right now I am attempting this by first using a Physics.OverlapBox() that uses the collider's bounds extents and its position to get nearby colliders.

I am then getting the direction and distance of the penetration using Physics.ComputePenetration() (I am filtering to focus on the deepest penetration)

I am then getting the "Contact point" by using Physics.ClosestPoint() in the inverse direction of the "direction" output of ComputePenetration.

From there I am attempting to apply a force at the contact point but I am having a few issues.

The box rests slightly within the collision surface.
The box when rotated will very painfully slowly roll to correct itself, but overcorrect and roll-oscillate infinitely.
I also am not sure about how to go about friction.

#

I guess I should also mention, I am at the moment attempting this all by adding forces to a rigidbody,

wintry crescent
topaz ocean
#

im trying to handle collision manually so I have access to friction forces and force transfer between bodies

wintry crescent
topaz ocean
#

because I dont have access to those things with a normal collider

wintry crescent
#

There's usually no point in recreating the entire physics collision system. There's an easier way for sure

topaz ocean
#

well, Im trying to make a wheel collider that uses a mesh without bouncing around like crazy so I need to
1 : apply a dampened collision force to prevent inconsistent acceleration
2 : calculate and retreive friction forces for good torque application
3 : accomodate the suspension hitting its bounds (any collision force not absorbed by the wheel should go to the Body)

wintry crescent
topaz ocean
#

I originally tried using jointed rigidbodies, which ended up being a wobbly mess. Ive considered retrying with articulation bodies but I remember those not having a very good angular velocity tolerance and I also would still like to get my hands on all the friction data

wintry crescent
# topaz ocean I originally tried using jointed rigidbodies, which ended up being a wobbly mess...

Depending on your situation, you might either want to use this asset https://assetstore.unity.com/packages/tools/physics/nwh-vehicle-physics-2-166252 or figure out how they're doing the things. They seem to have something that you need

Get the NWH Vehicle Physics 2 package from NWH Coding and speed up your game development process. Find this & other Physics options on the Unity Asset Store.

urban lance
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerCameraController : MonoBehaviour
{
  public float Sensitivity = 70f;
  public float RotationSmoothing = 0.1f;

  private InputAction LookAction;
  private Vector2 LookDirection;

  public Transform playerBody;

  private float xRotation = 0f;
  private float yRotation = 0f;
  private float xRotationVelocity = 0f;
  private float yRotationVelocity = 0f;

  private void Awake()
  {
    LookAction = new InputAction("Look", binding: "<Mouse>/delta");
  }

  private void OnEnable()
  {
    LookAction.Enable();
  }

  private void OnDisable()
  {
    LookAction.Disable();
  }

  void Start()
  {
    Cursor.lockState = CursorLockMode.Locked;
  }

  void Update()
  {
    LookDirection = LookAction.ReadValue<Vector2>();
    float mouseX = LookDirection.x * Sensitivity * Time.deltaTime;
    float mouseY = LookDirection.y * Sensitivity * Time.deltaTime;

    xRotation -= mouseY;
    xRotation = Mathf.Clamp(xRotation, -90f, 90f);
    yRotation += mouseX;

    float smoothXRotation = Mathf.SmoothDampAngle(transform.localRotation.eulerAngles.x, xRotation, ref xRotationVelocity, RotationSmoothing);
    float smoothYRotation = Mathf.SmoothDampAngle(playerBody.rotation.eulerAngles.y, yRotation, ref yRotationVelocity, RotationSmoothing);

    transform.localRotation = Quaternion.Euler(smoothXRotation, 0f, 0f);
    playerBody.rotation = Quaternion.Euler(0f, smoothYRotation, 0f);
  }
}``` in this code, does anybody see any obvious reason why at random times the camera will just jolt across the screen at mach 10
#

it's confusing me

somber nacelle
#

also obligatory "use cinemachine"

wintry crescent
urban lance
#

also, whilst im here, is there a good way to check if the game window has focus, when i do Application.isFocusedit doesn't do anything really

wintry crescent
urban lance
#

im going for more play in editor in focus

#

like actual game window in focus

wintry crescent
urban lance
#

alright

#

thank you

#

removing that delta time thing worked for the random jolts

#

so that's great

wintry crescent
#

That said, as a workaround, you could check if the mouse position is outside the rendered screen.

urban lance
#

now i have to make the character feel like its not just floating kekwarp

#

it looks ridiculous

swift falcon
swift falcon
#

What about private methods?

wintry crescent
swift falcon
#

Not accepted in interface

urban lance
#

should i do jump on press or release, what do you guys think?

wintry crescent
#

And if they're virtual, you can provide an implementation I think

urban lance
#

or should i make it a setting that you can chose your preference in a GUI

wintry crescent
urban lance
#

because press is faster

#

i've put it to press for now

dire crown
# swift falcon What about private methods?

An interface is just a contract that states any implementator of this interface will provide these objects. C# doesn't support multiple inheritance so your options are to use interfaces, or make your abstract class implement monobehaviour

urban lance
#

idk, personally im an unreal engine teacher so im trying to re-create the default character movement from unreal in unity

#

im used to it

#

also, question is there a way to make the public members be in categories

wintry crescent
somber nacelle
wintry crescent
#

That will work as a good separator, but won't be a complete box, you might also want to use [Space] if you want separation with no text

urban lance
#

wait i can google that

urban lance
#

ah

#

well i cant set default values then

#

shucks

wintry crescent
#

For the struct? Yea unfortunately
Unless you can make a constructor for it
Or a MyStruct.default with default values, something like Vector3.zero

#

And you can just assign it in code when declaring the variable

spring creek
wintry crescent
#

Idk about constructors, haven't used them in c# yet lmao

spring creek
#

And a blog

swift falcon
#

Is unity 2021 uses c# 8? or 9?

late lion
swift falcon
#

Um

#

is it right?

urban lance
#

im using 2023. something or rather

#

and that's C# 9

late lion
swift falcon
#

i want to use 8

#

even 9

late lion
#

If you're on 2021.2+, you can use C# 9 in either API compatibility level. Although .NET Framework 4.7.1 would normally be limited to C# 7.2, Unity's compiler bypasses that.

swift falcon
#

It seems i missed some things while configuring unity

swift falcon
late lion
#

It used to be called that, I think they just renamed it to .NET Framework.

somber nacelle
#

if you don't have a reason to switch from .net standard to .net framework, then don't

swift falcon
late lion
swift falcon
swift falcon
late lion
swift falcon
#

2021.3.18f1

late lion
#

Then yes, you can use default interface methods.

swift falcon
#

I will try the Net framework now

somber nacelle
#

it has to have a body to be private

swift falcon
somber nacelle
#

yes, you cannot have a private method on an interface unless it is a default implementation

swift falcon
#

I thought it would act like a contract

swift falcon
#

Oh

#

So i need a default implementation

#

Okey let me do it

somber nacelle
#

why do you even need a private method on an interface anyway if it isn't for a default interface method?

swift falcon
#

I dont understand how it works with interface right now

somber nacelle
#

interfaces are not a substitute for inheritance and should not be used in that way

#

interfaces are a contract that an object will implement specific public members to be accessed from other objects. a private member cannot be accessed from other objects so you shouldn't have them on your interface except for the case of a default interface method, which is really only useful for some very specific instances

swift falcon
#

So i will need 2 abstract classes with same codes πŸ₯Ή

somber nacelle
#

why do you need both a monobehaviour and a scriptable object with the same private fields and methods?

swift falcon
#

I am using Addressables system to manage my assets in memory. But my project wont Load Handle's all the time. So i made something for that and it acts like a "Loader&Unloader". But the loaded object could be a ScriptableObject or MonoBehaviour. So same implementation is needed. Or actually i could do Singleton or even Event system. But this one will be easy to maintain and understand.

somber nacelle
#

But it could be a ScriptableObject or MonoBehaviour.
why

swift falcon
#

The loaded object will contain some AssetReference's and they handling itself in memory.

somber nacelle
#

i don't really understand why you are trying to do it like this and it sounds like you're coding yourself into a corner tbh πŸ€·β€β™‚οΈ

swift falcon
#

Yeah i think thats it. Thank you for helping sir sadok

dire crown
dire crown
#

I highly recommend reading about composition versus inheritance

pure cliff
#

If you have an abstract method on an abstract class, it should be because that abstract class needs it for something

quaint rock
#

really sounds like you are overcoplicating things, thinking about future cases that are not concret yet

#

then with the more abstraction added, its harder to modify things as you go forward

quaint rock
#

can release things during the OnDestroy of the thing that loaded them

quaint rock
#

you can also do it without a custom inspector as well

urban lance
#

but not all of it

#

afaik

quaint rock
#

you just need to make classes that hold what you want with each group, and mark it Serializable

urban lance
#

yeah but then you cant define them inline

#

plus i learned something

#

so

#

win win

quaint rock
#

if not wanting to do that, or a custom editor, i will use the Header and Space attributes to add some orgnization to things as well

urban lance
#

i made it easy to use

#

and i learned something

#

so

#

im happy with that

#

i am 90% sure my code is deplorable

#

but it works

quaint rock
#

[SerializeField, Header("Physics")] private float Gravity;

urban lance
#

the code CatVibe

#

why did it include visual scripting

#

huh

#

not even being used

#

i find it really funny how the code for the movement component is smaller than the editor tool

quaint rock
#

welcome to UI code

#

often happens, also find my unit tests are often larger then the code they test

urban lance
#

i like to think im good at making games but the problem for me switching from unreal is the names of everything

#

i know what things do but i dont know that i know that

#

because the names are different

quaint rock
#

thats not a huge problem, some searching and docs can solve that

#

the concepts and how to solve problems are harder

urban lance
#

well C# was one of my first languages

#

so i know C# pretty well

#

but i learned C++ and i now teach unreal engine

quaint rock
#

yeah but a game engine is like a massive library, and you do end up handling a lot of thigns in patterns not common out of games

urban lance
#

i decided i'd give unity a shot again, idk why i stopped using it tbf it's alright

#

unreal engine has too many features

quaint rock
#

have used both, and in house engines

urban lance
#

it gets me side tracked, unity is clean

#

not distracting

quaint rock
#

find unity fights me less when you game design does not aling with how hte engine wants me to work

urban lance
#

and as a bonus i dont have to deal with that pesky language we all call C++

quaint rock
#

always felt unreal is more oppinoiated about how you do things

urban lance
#

especially in blueprints

#

unity is a pain to start off with

#

but once you've gotten going its much easier imo

#

unreal gives you everything

quartz folio
# urban lance

This is all very redundant. If you want to make a slider you just add [Range(min, max)] above your field.
If you want to make a foldout, you can just put your fields into a serializable struct.
Generally when making custom editors 90% of things should be using PropertyField so it uses the PropertyDrawer associated with the element and you don't have to manually specify the right type of editor control that can draw the type

urban lance
#

which is annoying

quaint rock
#

it offers less out of the box, but i do find building your own tooling for your games exact use cases is much easier in unity

urban lance
quaint rock
#

extending the editor in unreal is a pita

urban lance
#

unreal engine is soooooooooooooooooooooooooooo bad for 2D games

#

if you make a 2D game in unreal you're a masochist

#

i hate unreal's 2D engine

quartz folio
urban lance
#

its so bad

quaint rock
#

but yeah the UI things you did all possible via attributes, and creating classes as containers

urban lance
#

unreal's Paper 2D is so deplorable

#

i cant stand it

#

and i teach unreal for a living kekwarp

#

im supposed to advocate unreal kekwarpboom

#

anyways time to sleep

uncut lintel
#

In VScode, when I type three slashes "///", the lines below are automatically generated. How can I disable this so that I can type multiple slashes in a row without this happening? I've tried googling this but all I can find are people trying to MAKE it happen. Thanks.

/// 
/// </summary>```
quartz folio
#

Why would you want to disable that?

uncut lintel
#

it's annoying

#

I sometimes draw lines in my script with a bunch of slashes lol

quaint rock
#

its a useful feature actually

quartz folio
#

Why are you using triple comments if you're not writing a summary?

quaint rock
#

the summarys show up in your auto completion

uncut lintel
#

how do I disable it?

quartz folio
quaint rock
#

its a way to document functions

quartz folio
#

It appears when you hover functions

uncut lintel
#

what setting disables this behavior? I don't want any auto completion.

quartz folio
#

I have no idea, because it's an extremely helpful thing

uncut lintel
#

it has literally never happened until today

quaint rock
#

why not just draw lines in a different way
// ==========================

quartz folio
#

Why not just use a different line, like anything in between a multi-line comment /*asdasdasdasdasd*/

quaint rock
#

the xmldoc feature is really useful for documenting the public api of your stuff

quartz folio
#

seems pretty common too πŸ˜„

uncut lintel
#

because I'd have to replace 50 lines so that the formatting matches

#

I can find and replace but I'm used to it this way

quartz folio
#

I would avoid stubbornly sticking with a format that isn't great

sleek bough
quartz folio
#

Also common

dire crown
uncut lintel
#

VS Studio has a setting called "generate xml documentation comments for ///". What is the equivelent setting in VScode?

quartz folio
#

Nobody knows because nobody here would have tried to turn it off

#

Everyone would be just googling for you

uncut lintel
#

it was off until it wasn't.

dire crown
#

So then what'd ya change

quartz folio
#

I imagine you were just doing it in contexts where it won't autocomplete a summary

#

either that or it was introduced with the C# Dev Kit package that the VS Code Unity extension was recently updated to

quaint rock
#

seems weird if it was since its not a feature for unity, but a general C# thing

dire crown
#

There's a unity for visual studio code extension that gets updated p regularly

uncut lintel
#

this started happening after an update

warped bane
#

Im working on a 2d game where you control a 2d rigidbody, this controlling is done inside fixedupdate(). The rigidbody is tracked by a camera with a smooth follow inside of update(). when the camera follow it looks like the player is stuttering because my monitors refresh rate is higher than the rate of the physics loop. Is there a more proper way to do this that avoids this issue?

quaint rock
#

@warped bane try using LateUpdate instead of Update for the camera follow logic

warped bane
#

that doesnt change much, the issue is is that the player is not update often enough, due to it being physics based

quaint rock
#

then you would need some sort of interpolation over time on the camera

#

would use something like Vector3.SmoothDamp to move the camera to a target over multiple frames, and a set speed

uncut lintel
warped bane
#

I found a solution, i had to set the player rigidbody to interpolate, so that it moves every update instead of physics update

#

ah yep lol

#

thanks for the help

uncut lintel
#

I don't think this server is actually very reliable for getting good help

dense tusk
#

ello lads. i've got some prefab assets that i've combined together and put under an empty parent object. i wanted to know if there was a way to check from one of the child objects if the parent object had another specific child object. the way i'm trying to do it feel very roundabout, and i'd rather ask first before i waste my time with an excessively complex method

warped bane
dense tusk
#

i'm doing this from a script that checks for an interaction with one of the child objects, not from a script that is already on the child object.

quaint rock
uncut lintel
#

You could track this with code, simply using a public bool that you set when you add the object you want to track

sleek bough
sleek bough
uncut lintel
#

As stated, a forum would be much better. This server is out of date.

quaint rock
#

go to the forum then

warped bane
#

especially with a server this big

sleek bough
tawny elkBOT
#

πŸ’¬ Have a question that requires a more detailed explanation? We suggest using the Unity forums https://forum.unity.com/ to ensure your question is answered more effectively.

uncut lintel
#

it's not very active or speedy but it's true, probably way more reliable
https://forum.unity.com/

frosty sequoia
#

Trying to get the mouse position but because I'm using a canvas the mouse isn't even in the playable area, it's on the canvas. How do I convert the mouse position from its real position to what it would be in the playable area?

quaint rock
#

@frosty sequoia depends on your camera type is is ortho or perspective?

frosty sequoia
#

Ortho, sry for not clarifying lol

quaint rock
#

mouse position is in screen space, this converts it to world

#

for perspective its a little move involved, since you need to do a ScreenPointToRay and cast into the scene

#

but for ortho that should be enough, will give you a point on near plane of the camera based on a screen point

frosty sequoia
#

Yeah I'm using that but doesn't that just give me the mouse location that's on the canvas? I want to convert that position to where that would be in the playable space

quaint rock
#

are you calling it from the camera that renders the world and not the UI

frosty sequoia
#

How can I call it from the UI?

quaint rock
#

well if you want it for the playable space would you not want to do it from the games main camera?

#

or are you needing the ouput to be in canvas space?

frosty sequoia
#

It needs to be in the canvas space

quaint rock
#
RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.RectTransform.rect, Input.mousePosition, uiCam, out var localPoint)```
wary mortar
#

Im running into an issue... I have a QuestManager, with questTasks inside with [SerializeReference] attribute. If I change scene during a specific task, the reference in the next task is set to null, even although everything seems correct in the inspector, the object is still there

#

It doesn't look like a bug in the QuestManager itself, but something within unity

#

BTW I am using Odin Inspector

frosty sequoia
short ridge
#

Quick question, if a Coroutine begins on an object, then the object is destroyed, does the coroutine still execute?

quaint rock
#

nope

short ridge
#

πŸ‘ cheers

quaint rock
#

the coroutine executes on what ever called StartCoroutine

#

so it is possible to run the function from 1 thing on a other objects StartCoroutine if needed

#

disabled objects also do not tick coroutines along

short ridge
#

Currently trying to use "if object still exists, do this after x seconds", so this should work out

frosty sequoia
# quaint rock https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html

So this does convert the screen position to the world position like in the playable area where the camera is pointed at and not where the canvas is, which I didn't know. So that should all be fine but I'm trying to figure out why my mouse doesn't line up with where it should? Like what my mouse says is 0 y is actually like 16.75 y? Does anyone have any ideas as to why this is

quaint rock
#

its hard to say without knowing more about the scene setup

#

but it takes a screenspace coord and gives you a worldspace coord that would be on the near plane of the camera

#

its mostly only useful for a ortho camera

frosty sequoia
#

I am using an ortho camera. I can't really send any screenshots cuz my internet's out so I'll just send a photo

quaint rock
#

yeah should be fine, if anything is wrong i would expect the z to be wrong

#

since it will be close to the cameras z coord

frosty sequoia
#

The plot thickens. Found out that the bottom left corner is accurate. Which makes a lot of sense now that I think of it actually

worn stirrup
#

Hey all, how do I reduce the speed an object rotates based on its difference in rotation to another? I'm trying to slowly reduce how much AddTorque I apply to slowly rotate to match a "ghost"

#

that way when I stop input, the physical version still seeks the ghost position

#

Same "physics object follows ghost" physics concept as VR, but in 2D

wary mortar
#

Nevermind, it was my code lol

worn stirrup
#

Welp I've constructed some sort of monstrosity so here goes

#

clawLeft.AddTorque(clawArmSpeed * (360 / (clawLeft.transform.rotation * Quaternion.Inverse(clawLeftGhost.transform.rotation)).eulerAngles.z));

#

this isn't helping at all so if anybody has any suggestions πŸ˜…

prime sinew
#

then you multiply your torque force by that

worn stirrup
#

ooooo

#

looks right at a glance

prime sinew
#

i'd be interested to see what you come up with if it works ^^

#

not sure if there's an InverseSlerp

#

since you're using rotations

quaint rock
#

dot product of the forward vectors would give a similar 0-1 value as well

#

well in that case -1 to 1

worn stirrup
#

that actually might work better so I don't have to worry about when to inverse, it would just know

#

Wait that sounds wrong

#

idk I'll try that if I struggle with this

#

uhh

#

Wouldn't I need to be able to calculate how far it is from its hinge angle limit, and that would need to figure out the direction it's coming from frame?

#

hehe guess I'll be tinkering for another hour

#

thanks for the suggestions, gonna need to read for a while probably

worn stirrup
#

oh yeah inverslerp is going great, just gonna take a lotta optimizing now, thank you again!

prime sinew
#

i havent used it personally

worn stirrup
#

I'm still having some issues getting it to work perfectly actually, but this is my WIP Mathf.InverseLerp(-20.5f, clawLeftGhost.transform.rotation.z, clawLeft.transform.rotation.eulerAngles.z)

#

but it's directional, so that's only for the left to right rotation

prime sinew
#

ah I see

#

thanks for sharing regardless πŸ™‚

uneven slate
#

when scrubbing floats in the inspector, is there a way to increase the resolution of it? holding alt for 0.01 isn't fine enough for this case

nocturne grove
#

I meant the "line" that designates perpendiculars of both

#

That way I can just average them to make the "corner normal"

#

Unity's script reference is making me think I have to go through all the paths in a polygon collider and find the pair of points I need to do the math to get that myself

spring patio
#

while (transform.position.y < 4)

    {
        rb.velocity = new Vector2(0, speed * Time.deltaTime);
    }

Why does this freeze Unity and how could I fix it?

prime sinew
#

make sure you set speed to something other than 0

#

and that it'll lead your transform.position.y to less than 4 eventually

nocturne grove
#

Make it an if (transform.position < 4), and it shouldn't crash

#

Or you need to check the speed and have that be part of the while loop's break requirement

spring patio
#

but doesn't rb.velocity already alter the gameObject's position to above y4?

nocturne grove
#

No

#

That means it has that velocity

#

That doesn't mean the object is physically moving

#

That means it will move next time the rigidbody updates it's position

#

However, since the position never changes during the while loop, you created an infinite loop

spring patio
#

ooo ok

#

tysm :0

nocturne grove
#

np

worn stirrup
#

My progress but issue, 1 - Mathf.InverseLerp(20.5f, clawLeftGhost.transform.rotation.eulerAngles.z, clawLeft.transform.rotation.eulerAngles.z) is working correctly and returns a value that shrinks as it approaches the rotation

#

Mathf.InverseLerp(-20.5f, clawLeftGhost.transform.rotation.eulerAngles.z, clawLeft.transform.rotation.eulerAngles.z)} the exact same equivalent, but with a negative number, always returns 1

#

does it not take negatives ;-;

cosmic rain
night harness
#

Hey friends, back at it again with a question. I have a ScriptableObject with some values and I want a bunch of my gameobjects to grab those values. Right now they grab them on update but I want them to be more observer based and only grab them if they change. I'm pretty inexperienced with getters and setters but is there a good way to handle this with a scriptableobject? initially i wanted to use a unityevent or something like that but of course i can't do that in a scriptableobject

cosmic rain
pure cliff
# night harness Hey friends, back at it again with a question. I have a ScriptableObject with so...

I have implemented some example code for creating a pretty solid PropertyChanged Pub/Sub system, its not on a scriptable object so you'd have to copy paste the code and modify PropertyWatcherBase to inherit from it, but, aside from that the rest should work fine

https://gist.github.com/SteffenBlake/ace74a893d0b16c30a7eb2a42d6d9230

So the one tweak you would make, I believe is just:

 public abstract class PropertyWatcherBase<TSelf> : ScriptableObject
        where TSelf : PropertyWatcherBase<TSelf>
    {
#

I have the gist setup to largely just be copy paste / drag and drop in, it should largely work as is, and you can see the example code snippets in the comment I posted on that gist on how you use it, it's pretty easy to use and IL2CPP compatible

night harness
cosmic rain
night harness
#

I can't run code in a SO, no?

nocturne grove
pure cliff
cosmic rain
night harness
#

πŸ€”

cosmic rain
worn stirrup
#

oh lol my values aren't negative

#

It's using addtorque, obviously it loops to 360

pure cliff
#

I would also recommend @night harness, personally, you drop the scriptable object part entirely and just use injected POCOs via dependency injection, cuz scriptoble object singletons add a lot of extra work that really doesnt serve much purpose

nocturne grove
pure cliff
#

once you break free of the limitation of needing to make all your random scripts and code have transforms in the world and instead have actual ephemeral services that just... run and do stuff, without having to exist "in" the scene, life gets a lot easier

night harness
#

You threw a lot of perms at me that I might not be ready for at this present moment. On a higher level I do understand where your coming from though, I am a little chained down by my short visioned unity pilled-ness

pure cliff
#

POCOs just mean plain ole classes, not scriptables, not monobehaviors, just class

night harness
#

at the very least it's just a ref. i grab from my gamemanger singleton that I need anyway so it's not too bad but yeah im slowly wrapping my head around detatching myself from actual gameobjects

#

I actually had that revelation yesterday with the detection stuff I was doing

pure cliff
#

Id say a solid 95% of my code is just on POCOs that just run in the background as a service, no need for all the weird unity stuff, they just run and they "just work"