#archived-code-general

1 messages · Page 396 of 1

wheat spruce
#

will AddComponent actually construct it? Because I need to ensure that by the time the SimpleRectangle exists as a component, its properties will have been constructed

glacial shell
#

Hey does anyone have a good resource to change geometry in unity gui?

heady iris
knotty sun
#

yes, addcomponent will call awake

vestal arch
#

(why are they serialized anyways if you're gonna assign them)

heady iris
#

Note that there is nothing stopping you from giving your objects a constructor. It's just that this can result in unexpected behavior

#

For example, Unity applies serialized properties after the constructor runs, so it'll stomp on any values you store in your serialized fields

wheat spruce
heady iris
#

we already had a very long discussion about this, yes

wheat spruce
#

I still dont see the inspector as being useful for much more than doing some basic debugging

leaden ice
wheat spruce
#

not for me at least, I understand the purpose and utility of the inspector

heady iris
#

the entire point of the inspector is to configure objects

wheat spruce
#

any configuration I'm doing, largely is going to be done via code

leaden ice
#

You can do whatever you'd like, just pointing out what the inspector is intended for, and what it does best.

heady iris
#

For example: my Entity class references a list of "perspectives", which are ways you can view the entity when possessing or observing it

#

(entity index is debug information 🤫 )

heady iris
#

I create as many as I need and then put them in the list.

#

My HumanoidLocomotion class has fields for things like the footstep audio sources and the foot transforms. It would not make any sense to try to populate these fields via code: this is configured per-entity.

hexed pecan
#

And what do you mean with Unity gui

wheat spruce
#

maybe once the garden tool is fleshed out, I'll do more with the inspector

glacial shell
#

Unity UI system?

wheat spruce
#

change geometry in what way

glacial shell
#

i want to achieve something like this

hexed pecan
glacial shell
leaden ice
#

You shouldn't crosspost

glacial shell
#

sorry i didnt see that channel before

leaden ice
#

this channel is for code. And wdym, you asked there first

glacial shell
#

no i asked here first

leaden ice
#

well it's a UI question.

tardy tendon
#

Anyone know why this for loop isn't working? It works when I do it once, but once I stick it in a for loop to do 5 times, it doesn't instantiate anything...

for (int i = 0; i < 5; i++)
                            {
                                currentSpread = Mathf.Lerp(0.0f, GameManager.instance.levelManager.currWaterPistol.attributes.maxSpreadAngle, 
                                    GameManager.instance.levelManager.currWaterPistol.attributes.accuracy / 
                                    GameManager.instance.levelManager.currWaterPistol.attributes.timeToMaxSpread);
                
                                fireRoation = Quaternion.RotateTowards(fireRoation, Random.rotation, Random.Range(0.0f, currentSpread));
                                
                                GameObject tempProjectiles = Instantiate(GameManager.instance.levelManager.projectile, GameManager.instance.levelManager.projectileSpawn.transform.position, 
                                    fireRoation);
                                tempProjectiles.GetComponent<StraightProjectile>().hitPoint = hit.point;

}
knotty sun
#

How do you know it's not working? I see no debugging in your code

leaden ice
#

check your console

#

My guess - it's doing exactly what you told it to do and the projectiles are probably colliding with each other and destroying themselves immediately

#

but - start learning to debug your code.

tardy tendon
#

I have been debugging... I deleted lines so I didn't post too much in Discord.

heady iris
#

If the code is too long, then use a paste site

leaden ice
#

if you debugged you should explain what debugging steps you took and the result of those steps
It should be trivial to confirm your loop is indeed running 5 times as well as Instantiate

heady iris
#

Don't show us something different from what you were actually running

#

This can conceal problems, notably..

hexed pecan
simple sable
#

Is there a way in Unity to create a script that prevents specific tilemaps from being editable in the Tile Palette window? For example, I want to make sure that TerrainDisplay can only be updated via a script based on TerrainData, and avoid accidentally editing it manually.

heady iris
#

Perhaps you can instantiate the display at runtime so that it doesn't even exist in the scene?

#

That might be inconvenient.

#

I've thought about similar things (notably, making it so that i can only select certain tile palettes for each tilemap)

#

Alterantively, you could nuke the tilemap's contents during startup

#

so that even if you put some garbage in it, the tilemap is cleaned up

simple sable
#

Thanks for the answer. Ideally, I’d like the display tilemap to remain in the scene even when the game is paused, so I can see my changes in real time as I update TerrainData.

I’ve managed to write a script that prevents me from editing the tilemap, but it only works if the tilemap is selected in the hierarchy.

That said, I think the best approach might be to set it up so that hitting play (or perhaps using a custom editor script with a button) triggers the display tilemap to update by reading from the data tilemap. I was hoping there is another way but yeah.

worn star
#

i a getting arhument exception erro?

#

what is wrong?

#

I assigned everything properly in inspector

somber nacelle
#

what is the actual error and on what line

worn star
#

ArgumentException: GetComponent requires that the requested component 'Image' derives from MonoBehaviour or Component or is an interface.

line where i getcomponent image

#

can we not getcomponent Image

knotty sun
#

So you have a non Unity class called Image

worn star
#

I want To assign sprite of an Image in my canvas , randomly from an array of srptes

#

how do i do that

#

this method doesnt work

knotty sun
#

you first need to fix the problem of the Image class

worn star
#

but Image is inbuilt unity class

knotty sun
#

no it is not, hover over the word Image in your code and see what it says

worn star
#

hmm yeah

#

it says not a unity component

knotty sun
#

what does it say exactly

worn star
#

not a unity component

knotty sun
#

does it not show you a namespace for the class?

worn star
#

yes

somber nacelle
#

remove the UIElements namespace, that is the incorrect one. you want UnityEngine.UI.Image

knotty sun
#

so you are using UIElements.Image and you need UI.Image

worn star
#

damn

#

thanks man

knotty sun
#

It really helps when you read the full messages

worn star
#

yeah i see

#

didnt know Ui, UI elements are different 😭

dire marlin
#

my joystick in my game is not working. im using almost all joystick packages and when using the joystick it works perfectly fine in editor (and in simulation) but on my real phone it doesnt work

leaden ice
#

What kind of joystick are we talking about here? Where's the code?

spare fjord
#

Hey,
I have a school project where I want to create a school platform for schools in VR. I want to create a kind of meta menu where the school loads their website as a home menu via unity webview. I am trying something with chatgpt and google but it aint working out. I saw this video: https://www.youtube.com/watch?v=q3swlSP1mRg&t=4s but i can not find the sample or something. Would someone like to help?

dire marlin
#

this joystick works in all of my other projects

#

and my other projects were unity 6 aswell

#

so im not sure why touch isnt being registered

leaden ice
dire marlin
#

and i've tried making it as close to the original as possible

leaden ice
#

Maybe another UI element or canvas

dire marlin
#

except for the note

#

but the joystick should be overlayed on top

leaden ice
#

Try disabling everything else

#

Also make sure you have an event system in the scene

dire marlin
#

im using old input system btw

hidden compass
#

dynamic joystick? idk the terminology for it

dire marlin
#

sorry i didnt message before but i figured it out: i had two joysticks in the scene

#

and for some reason i cant use two at the same time 😔

hidden compass
#

this.. i ask b/c im looking for an alternative

hidden compass
#

multitouch joysticks

dire marlin
hidden compass
#

im sure theres assets out there..

#

i haven't a clue about mobile sorry

hidden compass
#

the asset i showed in the video is actually this asset ^ i believe

#

it doesn't say it specifically in the details tho.. (just tagged).. and i cant remmeber all the demo's they had

sly shoal
#

Hi, I'm running into a deltaTime-based issue with a function that pulls the characters downwards with increasing velocity when falling.

I'm calling AddGravity in Update. It reads the player's velocity (rb.velocity is saved to CurrentVelocity) and I add an additional gravity force to it. Here's the relevant code snippets.
https://paste.ofcode.org/iXKKHGLQWHUJqsCCSSdBnp

I realised that this extra gravity performed differently with different frame rates. The video shows the same jump performed on two different refresh rates (around 120 and 200+) and one character clearly lands quicker than another. Printing out CurrentVelocity over time confirmed that the 160 refresh rate character had a slightly higher velocity by the time they landed on the ground.

I'm fairly confident the issue I'm encountering is explained in this video https://youtu.be/yGhfUcPjXuE?t=502. A linear increase in velocity over frames. And the solution is to calculate the new speed by multiplying by deltaTime and then use deltaTime again when changing transform.position.

This issue is, I'm working directly with velocities here, not positions. So I'm not quite sure how I would carry over this principle to my code. Anyone have any ideas?

dire marlin
hidden compass
#

gonna have to home-brew it

heady iris
#

But the difference you're seeing is huge

#

Or maybe I skipped ahead too far

#

I went ahead to the part where they add half of the acceleration before moving and half of it after

#

at around 11:56

heady iris
#

When do you actually call AddGravity?

sly shoal
# heady iris When do you actually call AddGravity?

my characters run on an FSM. in the air state, I have this line in my update method

if ((_character.isJumping && jumpInputCancel) || (_Movement.CurrentVelocity.y < _characterData.gravityKickInVel))//character.Movement?
{
    _character.AddGravity();
}
heady iris
#

Are you falling slower at higher framerates?

sly shoal
#

faster

left olive
heady iris
#

well, there are no forces here

#

I don't know what this "MovementVector" object is

sly shoal
#

movementvector is just a vector2 that stores the velocity from MoveX and MoveY

heady iris
#

ah, I'd never seen the Set method before

#

I don't see anything here that'd make you fall much faster

sly shoal
#

you think there's something other than the frame rate at work?

heady iris
#

Does anything else modify the MovementVector?

sly shoal
# heady iris Does anything else modify the MovementVector?

ooh shit oopsie. the video i posted isn't a regular jump. its a movement ability with both an X and Y component. completely my fault for misreading the clip i posted.
the core idea is the same though.
I call this function to launch the player in a specific direction, and then the gravity stuff kicks in as i described

    {
        MovementVector.Set(angle.x * facingDirection, angle.y);
        SetFinalVelocity();
    }```
the added movement in the x direction here could account for why the discrepancy between the two frame rates is so drastic but i think the underlying cause (the AddGravity method) is the same
#

here's a video of both of us doing the same ability but without that gravity line. you can see it lines up pretty much exactly

heady iris
#

and where does angle come from?

#

I would like to see the entire script(s)

sly shoal
#

okey. sorry if its a little messy/unreadable. haven't got around to making it look good yet hehe

#

is there a preferred method for pasting entire scripts here

heady iris
#

!code

tawny elkBOT
sly shoal
#

❤️

#

i can post anything else you need but that should give a good overview of whats happening

pearl burrow
#

Hi! If i understand correctly if i need a class to call a method from another class its better to use a service locator, while if many class need to fire the same method of another class is better to use events? Can anyone enlight me on this? (avoid Dependency injection in this case)

leaden ice
#

Events reverse the dependency

#

If A has a reference to B and wants to call a function on B, we could reverse that dependency such that:
B has a reference to A, so B listens to an event on A in order to invoke the function on B

#

This means A doesn't need a reference to B

#

Instead B has a reference to A

#

That's the only thing events do really

pearl burrow
#

so can you explain me better the difference between the service locator and an event bus? they could act in the same exact way no?

pearl burrow
#

i mean its not bad to use it in this way

leaden ice
#

A service locator helps you find the service to call a function on.

The event pattern would reverse the dependency.

Let's use an example of a player with HP and a health bar UI element.

The player object could use a service locator to find the health ui handling object and call UpdateHealthBar() when the health changes to change the UI.

Alternatively, the player object could publish a "MyHealthChanged" event into an event bus.

The health UI can listen to that event and update itself. This way it's the health UI depending on the event it's listening to rather than the player object depending on the health ui existing.

leaden ice
#

The beauty of an event based system is that the publisher of the event doesn't know and doesn't care how many listeners there are

#

it's fire and forget

pearl burrow
#

all clear! thank you so much even tho i have one more question

spare dome
#

Is there any way to return multiple items in a function (I'm trying to return a boolean and a list)?

pearl burrow
#

ive made my own static event bus system which will fire any events given the event type. only problem is that the methods that describe events can't return anything (so void methods).. is it good to have callback that do so?

the structure is this

struct MyEvent : IEvent { 
  public int value;
  public Action callback;
}

then i can subscribe doing

public class MyClass : MonoBehaviour {
  private void Awake {
    EventBus<MyEvent>.Subscribe(MyEventMethod);
  }
    
  private void MyEventMethod(MyEvent evt){
    //do something
    evt.callback?.Invoke();
  }
}
leaden ice
#

For example Physics.Raycast returns a bool indicating if there was a hit or not, and returns a RaycastHit struct as an out parameter

pearl burrow
#

im not using the unity events but i implemented my own thats why

spare dome
#

oh nevermind, I just found the documentation for it

leaden ice
# pearl burrow ive made my own static event bus system which will fire any events given the eve...

This seems backwards to me? Or weird? Maybe I'm missing something? I would expect basically:

struct MyEvent {
  int some;
  bool random;
  float data;
}

public class Publisher {
  void PublishEvent() {
    MyEvent e = new MyEvent();
    e.data = 4;
    EventBus.PublishEvent(e);
  }
}

public class Listener {
  void Awake() {
    EventBus.Subscribe<MyEvent>(MyEventHandler);
  }

  void MyEventHandler(MyEvent eventData) {
    print("Received event with data!: " + eventData.data;
  }
}```
#

It's weirtd to me that the listener function would receive the delegate and then.. be able to invoke it... again?

#

Maybe I misunderstood your example

pearl burrow
#

oh i forgot one piece!
ill copy your to be faster. So the problem is when i want to do something like

  if(intValue > GetIntValueFromAnotherClass())

what im doing is this in the publisher

struct MyEvent {
  int intValue;
  Action callback;
}

public class Publisher {
  void PublishEvent() {
    MyEvent e = new MyEvent();
    e.intValue = 4;
    e.callback = DoSomething();
    EventBus.PublishEvent(e);
  }

  void DoSomething(){
  }
}

public class Listener {
  int listenerIntValue = 0;
  void Awake() {
    EventBus.Subscribe<MyEvent>(MyEventHandler);
  }

  void MyEventHandler(MyEvent eventData) {
    if(eventData.intValue > listenerIntValue){
      eventData.callback?.Invoke();
    } else {
      Debug.Log("Its not greater!")
    }  
  }
}```

Is it more clear?
leaden ice
#

why would the publisher provide a callback for the listener

#

And why not just ahve the publisher do this:

    EventBus.PublishEvent(e);
    DoSomething();```
pearl burrow
leaden ice
#

Ok I guess you're now talking about having the publisher retrieve a value from a listener

pearl burrow
#

yes yes

leaden ice
#

which is usually not something you do in event-based architecture

#

usually events are "fire and forget"

cosmic rain
#

That's sort of against the event pattern

leaden ice
#

and we don't care who is listening

#

mostly because then what happens if you have multiple listeners?

#

Which one would we retrieve the return value from?

#

or zero listeners

pearl burrow
#

yeah so im lost T_T thats why ive put a callback in there

leaden ice
#

What's the use case for this?

#

It doesn't seem to fit into an event pattern

pearl burrow
#

i have instantiated object that need to check for example onclick if i have enough "stamina" to click. Since i dont wanna make a singleton for everything and the stamina is stored in its own manager i was calling an event to do so

leaden ice
pearl burrow
#

if thats true than this instantiated object has to do something

leaden ice
#

and have itself turn on and off in response

pearl burrow
#

so the object has a int value that tells how much stamina it would consume. I need to give this value to the manager check if i have enough stamina and then tell to the object "ok you can proceed"

leaden ice
#
class SprintButton : MonoBehaviour {
  EventBus.Subscribe<StaminaChangedEvent>(StaminaChangedHandler);
}

void StaminaChangedHandler(StaminaChangedEvent evt) {
  myButton.interactable = evt.newStaminaValue > 5;
}```
pearl burrow
#

but when the event is fired i have already clicked on the object

leaden ice
#

Why would it be

#

why not just make the button unclickable before hand, based on when the stamina changes

#

Also I guess you're just really trying to avoid the button having a reference to the stamina manager?

#

Why can't we just do if (StaminaManager.Instance.CurrentStamina > 5)?

#

or if (StaminaManager.Instance.TryConsumeStamina(5))

pearl burrow
#

because its not only one button, lets say its a stamina system for those idle games. there are many of these objects and everyone has its own stamina consuming value. Since you get stamina every x minutes i should enable buttons every time?

#

yeah i was trying to avoid singleton patterns. i have already few and im refactoring all my code for more readability

leaden ice
#

the buttons listen for the stamina change events and enable/disable themselves when there is enough stamina or not, sure

leaden ice
pearl burrow
#

its a static class

leaden ice
#

But if you really don't want to do StaminaManager.instance you can keep local copies of the stamina level in each of these things

pearl burrow
#

you can subscribe unsubscribe and raise from everywhere

pearl burrow
#

so the disable enable is the best thing

leaden ice
#
class SprintButton : MonoBehaviour {
  int energy;

  void OnEnable() {
    EventBus.Subscribe<EnergyChangeEvent>(EnergyChangedHandler);
  }

  void EnergyChangedHandler(EnergyChangeEvent evt) {
    energy = evt.newEner;
    // Check whether to enable or disable whatever button(s)
  }

  void OnButtonClick() {
    if (energy > 5) Consume();
  }
pearl burrow
#

im sorry lets not call it stamina, but energy or idk clicks. Stamina can give different ideas

leaden ice
#

sure it doesn't make much difference

pearl burrow
#

it was really this simple

#

tysm

#

one last question! would be bad performance-wise to call an event in the update function every frame, or in a coroutine or whatever?

leaden ice
#

generally fine

pearl burrow
#

im still stubborn about one thing. I have another use case for this example.
Lets say i have my grid inventory. I have an itemobject that store its quantities and the item can be 1x1 1x2 or whatever. every time i click it i need to check if the inventory is full. if its not i decrease the quantity of the item.
You might say "have the item listen to the inventory to know when its full" but if the item has different sizes what do i do

#

or maybe i let the inventorymanager to store all the items (and their quantity) and just raise the event to check and decrease?

#

it make sense, why the item should know its quantity. The manager does that! (no?)

tulip breach
#

How can I make my regular animations override animation rigging animations

narrow sapphire
narrow sapphire
pearl burrow
#

i have but i dont have the reference to the inventory manager if the item is instantiated at runtime (a prefab)

cosmic rain
#

If you need to play some kind of effect depending on whether the item was added or not, the inventory ui could be having an actual reference to the inventory instance and call an actual method that returns true/false. Then it could play the desired effect, or call some method on other ui/invoke a method.

cosmic rain
pearl burrow
#

yes i wanted to avoid that since i instantiate not many but not few objects at runtime and everyone should have a reference

cosmic rain
pearl burrow
#

so do you think the inventorymanager should update the itemdata? so holding all the reference of all the items

#

thats what you suggest?

cosmic rain
#

Inventory instance. Inventory manager sounds like something that would manage all the inventories in the game.

#

Though, if you only have one, it might be fine.

pearl burrow
#

yes the inventorymanager for now holds one inventoryinstance

cosmic rain
#

Then yes. Inventory manages the items in it. It logically makes sense.

hardy pasture
#

So I can't just subscribe for InputAction being performed in Awake:

    void Awake() {
        Action1.action.performed += _ => SwitchToNextCharacter();
    }

And let C# unsubscribe on when the my PlayerInput component and Action1 objects are destroyed?
After I restart the scene with Application.LoadLevel(0);, I get null object reference errors in the console when I perform actions. And so I solved it by creating a function and subscribing on Awake and then unsubscribing on OnDestroy:

    void Awake() {
        Action1.action.performed += Action1_performed;
    }

    void Action1_performed(InputAction.CallbackContext obj) {
        SwitchToNextCharacter();
    }

    void OnDestroy() {
        Action1.action.performed -= Action1_performed;
    }

It works but now I'm forced to use named functions, because I can't do Action1.action.performed = null on destroy to make all handlers unsubscribe. Is there a way to simplify this: use lambdas instead of having to create named functions and maybe reinitialize the InputAction or InputActionReference, so I don' have to manually unsubscribe each even handler myself?

spring basin
#

is there a dedicated channel for in app purchase?

#

right now i have this weird problem where Unity

#

UnityPurchasing.Initialize(this, builder);

#

gives me no callback

#

like failure/success nothing

#

im trying to do it for an unreleased android game

#

i've already added the RSA public key in the unity dashboard and it shows up in my editor

thin aurora
#

Whatever the case, you will have to store your lambda somewhere. Either a named method or a delegate will do.

#

And regardless it should be done anyway because it's more readable.

hardy pasture
#

Weeeeeeeell, RAII is better, because it works even when exception is thrown

#

And less code, too

worn star
#

hi lets say i have a class lobber which inherits from base Bullet

if i call -> this.destroy in Bullet class , will the lobber also be deleted?

hardy pasture
#

And there's a callback array as a backing property. Would be better if we could just reset the InputAction instead of manually unsubscribing and if it did it itself when the object is destroyed.

thin aurora
hardy pasture
thick terrace
#

i'd rather have it like that to be honest, it's better that you can only remove events you know you subscribed rather than it being possible for the whole array to be cleared from anywhere in the code

#

it's a little more inconvenient if you're only using it in one place, but it's worth it for cases where you might have multiple listeners being added and removed in various places

spring basin
#

any idea about the in app bug :P?

hardy pasture
# thin aurora Would it be possible to define a list of delegates which are subscribed and then...

You mean something like this:

    List<Action<InputAction.CallbackContext>> Action1Listeners = new();

    void Awake() {
        Subscribe(Action1, Action1_performed, Action1Listeners);
    }
    void OnDestroy() {
        Unsubscribe(Action1, Action1Listeners);
    }

    void Subscribe(InputActionReference InputActionReference, Action<InputAction.CallbackContext> ActionListener, List<Action<InputAction.CallbackContext>> ActionListeners) {
        ActionListeners.Add(ActionListener);
        InputActionReference.action.performed += ActionListener;
    }

    void Unsubscribe(InputActionReference InputActionReference, List<Action<InputAction.CallbackContext>> ActionListeners) {
        foreach(var Listener in ActionListeners) {
            Action1.action.performed -= Listener;
        }
    }
#

It works but

#

I already wrote my own Action and Axis abstractions, so that I can accept inputs in a character from different sources: PlayerInput or AI

#

Because the default InputAction only allows to accept inputs from physical devices

#

At this point it my PlayerInput component start to look a lot like what InputAction does

#

But not tied to physical devices and ability to take inputs from anything

chilly surge
#

That usually is a bit too much of a commitment (but it works really when if you really do commit to it), so in generally I suggest to just use a method and remember to unsubscribe manually.

thin aurora
#

I'd look into just manually making delegates then if I were you

#

You won't need to make whole methods and instead use the delegates. Just make sure to put them on class scope so you can use them properly

#

There's probably an automated way using weak references but at a certain point you should wonder if adding functionality like this is really going to improve anything

chilly surge
#

Weak references wouldn't work for automatic unsubscription.

thin aurora
#

A weak reference that triggers unsubscription on allocation is perfectly possible and there are .NET classes that use this system as a handle to finalize classes that were not disposed

#

But like I said, at some point you should wonder if adding a system like this would really benefit an application considering the code involved

#

Especially since this is not a case of possible forgetting to dispose and more a case of convenience

chilly surge
#

It wouldn't work for automatic unsubscription, a weak reference only guarantees that the referenced object can still be GC collected, but GC is not deterministic.
When a GO/component gets destroyed, GC doesn't immediately collect it so the weak reference will possibly linger for much longer depending on the mood of GC, and until it gets collected the weak reference is still valid and the action will still get called.

#

Weak reference data structures are memory optimization techniques.

thin aurora
hardy pasture
# thin aurora But like I said, at some point you should wonder if adding a system like this wo...

Yeah. Definitely. I just want to have a nice system for gathering player input and then passing it to the controlled objects.
At first, I thought I can put those InputActionReference and InputAction objects directly on my Character component, so that it could be controlled by the physical devices and then by AI and network controllers. But, apparently, I can't, InpuAction can only take inputs from physical devices.
So I created my own abstractions for Action and Axis and I take that on the Character and I pass it to the Character from my PlayerInput component.

#

It feels like I'm working around and against Unity's framework and not with it.

thin aurora
#

I'm not sure how well the add/remove operators on event properties work, but perhaps you can somehow fiddle with that and get a unique reference to lambda's that way. Unity also has an event system that (I believe) uses listeners and a way to remove all listeners at once, so maybe you can also use that

#

Addlistener/RemoveAllListeners

chilly surge
#

Lambda is reference type, you just need to hold onto a reference to it to unsubscribe.

thin aurora
#

And when removing the listeners, it can simply clear the list

#

Also, note you can make a delegate variable yourself and attach multiple methods on it. You don't necessarily need to use events and it might be a lot cleaner if you attach multiple methods on a delegate when working internally

chilly surge
worn star
#

does anyone know how getcomponent works internally ?

like i had a doubt if a game object has a script with class A which extends from B
will I will be able to use Getcomponent< base class> , even though its not directly atttached to the object

worldly hull
#

so due to mysterious reasons, my layout element cant work, like it doesnt do ANYTHING at all, so i might need to make my own script that simulates what it gonna do

so i gonna start with : how do u get the line count of a text

thin aurora
#

But GetComponent should work fine with base classes

#

With generic types, at least.

hardy pasture
#

Another question guys, how to setup 2 player input systems using the same physical device? Specifically, keyboard.

#

Am I going to have to define Player1 and Player1 InputActionReferences?

#

So I'll have to have double the actions for each action: for player1 and player2?

hardy pasture
#

Example: left player uses WASD for movement and YGHJ for actions. Player 2 uses arrow keys and numpad keys.

#

How do I set this up using this input system?

dusk apex
#

What have you tried so far?

hardy pasture
#

Nothing, I can only see doing it by duplicating actions in the input actions list. That's why I'm asking: maybe there is a better way of doing it by reusing the current input actions asset and input actions.

#

That's what I'm going to do if there is no other way, I just thought somebody would know a better way.

knotty sun
hardy pasture
#

When I jumped to the definition, Resharper downloaded the .pdb and then decompiled the class.

placid summit
#

Are those weak references usable in Unity?

chilly surge
cold parrot
chilly surge
#

As for Unity, I think there are some issues with weak references when you build with IL2Cpp, not sure about Mono.

#

But either way, weak reference is not a solution for automatic unsubscription.

swift falcon
#

Can the One shot audio gameObjects that are created by AudioSource.PlayClipAtPosition() be pooled? I've trouble to get them into an object pool

sudden hinge
#

Is there a way to increase the padding of FindIntersectingWord?
It works fine on PC, but on mobile you often tap just next to the word, which is very frustrating

placid summit
#

dunno what Microsoft.SPOT namespace is!

chilly surge
#

Yes there are quite a lot of weak data structures, it's not that they don't exist or do what they claim to do, but it's simply that what they do is not what automatic unsubcription needs.

placid summit
chilly surge
#

Well bad wording, what they do does not solve automatic unsubscription.

#

The use case and what the original question asks for, is for a way to automatically unsubscribe when a MB is destroyed, and "destroyed" is defined as "when OnDestroy Unity message is called."

#

What weak reference allows you to do, is to keep a reference to the object without preventing GC from collecting it, so when GC does collect it the object is automatically gone.

#

Do you see the problem now? "When OnDestory is called" is not the same as "when GC collects it."

placid summit
#

yes well it is true MBs are not very helpful - for me personally I use a lot of straight C# classes in Unity so it might solve some cases. But yes OnDestroy is a pain

oblique spoke
chilly surge
#

For automatic unsubscription, the point where unsubscription needs to occur rarely has anything to do with GC.

placid summit
strange cargo
# hardy pasture Example: left player uses WASD for movement and YGHJ for actions. Player 2 uses ...

Doing multiple players on one device is surprising involved. Check out https://discussions.unity.com/t/2-players-on-same-input-device/762490. But don't expect it to work with rebinding or players joining/leaving. I recommend checking out. https://u3d.as/3pzb

Get the Share InputSystem Device package from ShawnFeatherly and speed up your game development process. Find this & other Input Management options on the Unity Asset Store.

rain minnow
thin aurora
#

Equality comparison allows you to do that

#

If you'd truly make a system that applies weak references to classes, then you could build that in to save the trouble. But again, probably not something you want to add to your application to begin with

#

Also, it was just a general thought to give an idea of the possibilities. It's going to have edge cases, that wasn't the point of the message

swift falcon
rain minnow
chilly surge
swift falcon
rain minnow
hardy pasture
# strange cargo Doing multiple players on one device is surprising involved. Check out https://d...

In the second post they're suggesting to do this:

// Instantiate two players using a split-keyboard setup.
var p1 = PlayerInput.Instantiate(playerPrefab,
    controlScheme: "KeyboardLeft",
    device: Keyboard.current);
var p2 = PlayerInput.Instantiate(playerPrefab,
    controlScheme: "KeyboardRight",
    device: Keyboard.current);

But I don't see how to create different key bindings per control scheme. When I change the key bindings for an action in one control scheme, once I switch to a different one, the key bindings stay.

hardy pasture
#

This looks like it will create different instances of PlayerInput components with different control schemes, but since the button bindings are the same for both control schemes, I don't see how that helps to create separate controllers for player1 and player2 on the same device.

#

They're always the same

heady iris
#

notice how (GLOBAL) is appended to every binding here

#

if a binding is not assigned to at least one control scheme, then it'll be used by every scheme

empty kayak
#

Hey, i have a question. This is my first time doing a 3rd person project and im curious as to why my camera is shaking in build mode but not in the editor.

#
public class CameraFollow : MonoBehaviour
{
    public Transform CameraHolderPosition;
    public GameObject InputGameObject;
    [SerializeField] float Speed;
    [SerializeField] PlayerInput input;
    [SerializeField] Transform playerBody;
    Vector2 lookInput;
    [SerializeField] float lookY, sens, lookX;
    private void Start()
    {
        input = InputGameObject.GetComponent<PlayerInput>();
    }
    void Update()
    {
        lookInput = input.actions["Look"].ReadValue<Vector2>();
        Debug.Log(input.actions["Look"].ReadValue<Vector2>());
        Vector3 CameraHolder = CameraHolderPosition.position;
        transform.position = Vector3.MoveTowards(transform.position, CameraHolder, Speed);
        CameraSens();
    }

    void CameraSens()
    {
        lookX += lookInput.x * sens;
        playerBody.Rotate(Vector3.up * lookInput.x * sens);
        //lookX = Mathf.Clamp(lookX, -90, 90f);
        lookY -= lookInput.y * sens;
        lookY = Mathf.Clamp(lookY, -90f, 90f);

        transform.localRotation = Quaternion.Euler(lookY, lookX, 0f);
    }
}
quartz shell
#

Hello, i'm not sure ill do a great job explaining but i will try.
I am currently working on a system that takes a CSV file with ability data, serializes it and uploads it to scriptable objects that contain the ability itself.
when i save the actual data through a custom editor script it uploads the data to all the scriptable objects and works perfectly, but after restarting the editor/building, the data is gone.
is there a special interaction/property i have to give a scriptable object field in order for it to save after being updated through script?
i would like to specify i am not updating the scriptable object during run time, but only through a unity editor button that links to a script.

knotty sun
quartz shell
knotty sun
#

absolutely

quartz shell
#

i see, do i have to "resave" them to the same locations with assetdatabase?

knotty sun
#

not necessary, you just pass the SO object, I suggest you go read the documentation

quartz shell
#

i have read, i just didn't realize it fits my issue aswell i apologize.

#

i thought since i wasn't doing it at runtime it wasn't the same

#

thank you will update if this helps ❤️

knotty sun
#

you cannot, as standard, save an SO at runtime anyway except in the Editor

quartz shell
#
        foreach(ScriptableAbility ability in Abilities.Values){
            
            ability.abilityUpgradeData = new List<AbilityUpgradeData>();
        }
        upgrades = CsvReader.ReadCsv<AbilityUpgradeData>(filePath);
        foreach(AbilityUpgradeData upgrade in upgrades){
            if(upgrade != null && upgrade.AbilityName != null){
                
                #if UNITY_EDITOR
                    EditorUtility.SetDirty(Abilities[upgrade.UID]);
                #endif
                Abilities[upgrade.UID].abilityUpgradeData.Add(upgrade);
                Abilities[upgrade.UID].abilityUpgradeData = new List<AbilityUpgradeData>(Abilities[upgrade.UID].abilityUpgradeData); // Reassign to trigger change detection


            }
        }
        #if UNITY_EDITOR
            AssetDatabase.SaveAssets();
        #endif

    }

Even after setting all the objects to dirty before/after changes and saving the assets it doesn't quite save them after resetting

quick kindle
#

experienced dev, not all that sharp at C#, probably failing some basic OOP knowledge here:
I have a Piece class that holds data about a game piece
I have a ILoc interface, the Piece class has a reference to an ILoc
I have HexLoc and ReserveLoc as struct implementations of ILoc
At runtime a Piece's loc could point at a HexLoc or a ReserveLoc (or other ILocs as needed)
But during runtime I need to find out if a Piece is at a HexLoc, and I'm getting weird results
(At this point, there's no actual fields specified in the ILoc, its just there to let a piece exist in one and only one ILoc)
Is this the right C# approach for solving this? Or is there more Csharpey way to do it?

#

also seeing unexpected editor behavior, things i thought would be visible in editor are not. Piece is a serializable struct and it shows up, but the List<Card> and ILoc are not?

leaden ice
#

and Card would have to be a serializable type in order for List<Card> to be serializable

quick kindle
#

[Serializable]
public class Card { }

leaden ice
#

But during runtime I need to find out if a Piece is at a HexLoc, and I'm getting weird results
(At this point, there's no actual fields specified in the ILoc, its just there to let a piece exist in one and only one ILoc)
Is this the right C# approach for solving this? Or is there more Csharpey way to do it?
What do you mean by "weird results" exactly?

quick kindle
#

does it actually need to like... have something to serialize

leaden ice
#

Oh the other thing is that cards is a property

#

Unity doesn't serialize properties

#

only fields

quick kindle
#

oh snap ok

leaden ice
#

in fact it's a property that just returns a brand new list each time it seems

quick kindle
#

IDE telling me that structs cant initialize with cards = new List<Card>; that works if i switch the struct back to a class

#

im never quite sure when i should be deciding to use structs instead of classes

#

ok i switched my loc items back to:
public class Loc { }

[Serializable]
public class HexLoc : Loc
{
public TerrainTypeCode terrainCode;
public int altitude;
public Vector2Int coord;
}

[Serializable]
public class ReserveLoc : Loc { }

heady iris
#

Structs cannot have field initializers (at least, not in this version of C#)

quick kindle
#

yea

crisp bronze
#

I have a script for a custom MenuItem that spawns an empty gameobject. How would I make these automatically the children of the scene's current Default Parent? As of right now, they just go straight to the bottom of the hierarchy.

quick kindle
#

if i understand your q correctly, Instantiate has a second optional argument of a transform, if you pass a transform the prefab will instantiate as the child of the transform's gameobject

leaden ice
heady iris
#

That's probably an editor-only thing

#

you can mark an object to be the default parent for new objects you add

leaden ice
#

Ah interesting

#

Yeah that seems like an editor thing

heady iris
#

Are you trying to write editor-only code, or is this meant to work in the built game?

#

(I've never ever used this, but it'd be nice for building levels, now that I think about it..)

#

actually yes I should definitely be using this

crisp bronze
#

For spawning certain tools I've made like spawn points

heady iris
#

hmm, i don't see a way to get the current default parent

#

you can set it and clear it

robust dome
#

is it possible to determine the default parent gameobject

heady iris
#

well, there is one way...

#

create a game object

#

find out where it went

robust dome
#

i was really curiois about that

#

so there is no other way then hacking around 😉

golden lichen
#

what's the proper way to check if a gameobject has been destroyed in a unit test?
doing a null check doesn't work for some reason:
Expected: null But was <null>


    [UnityTest]
    public IEnumerator HoverOverOccupiedTile()
    {
        CommonInstall();

        _boardItem.DestroyItem();
        yield return null;

        Assert.That(tileManager.tiles.ContainsKey(new Vector2(2, 2)));
        Assert.Null(_boardItem); //Expected: null But was:  < null >
        //Assert.IsNull(_boardItem); //same result

        yield break;
    }
hardy pasture
#

Now, what's the prefab object

#

Since I'm doing it in code, what do I pass it?

#

I can't exactly pass it a path to the prefab.

heady iris
heady iris
#

well, yeah, you need to get a reference

#

that's nothing new, though

#

this is just like any other situation where you need to instantiate a prefab

simple egret
worn star
#
public class RichochetBullet : Bullet
{
    public override void Start()
    {
        base.Start();
        MoveForward();
    }

    public override void Update()
    {
        base.Update();
      
    }

    private void MoveForward()
    {
        rb.velocity = transform.right * bulletSpeed;
    }


    private void OnCollisionEnter2D(Collision2D collision)
    {
        
            Vector2 normal = collision.GetContact(0).normal;
            Vector2 direction = Vector2.Reflect(rb.velocity, normal);
        rb.velocity = direction.normalized * bulletSpeed;

        // Slightly move the bullet away from the collision point
        transform.position += (Vector3)(normal * 0.01f);


    }````
#

guys idk why my bullet gets stuck after collisions

#

doesnt reflect

hexed pecan
#

You can keep track of your velocity by storing it in a member variable each frame

#

Then you'd use that instead of rb.velocity here

worn star
#

it worked but tbh i dont understand

hexed pecan
#

So this line is supposed to reflect the velocity away from the collision, right?
Vector2.Reflect(rb.velocity, normal);

worn star
#

yeah

#

oh i see

#

i get it

hexed pecan
#

The physics system has already processed the collision. The bullet was already reflected

#

I think you could also skip the whole "store the last frame's velocity" and just do rb.velocity = rb.velocity.normalized * bulletSpeed
If you just want to keep the speed but let the physics engine do the reflecting

worn star
#

so update stores last frames velocity ,not current frame?

hexed pecan
#

You want to store the current velocity

#

Preferably do it in FixedUpdate tho

#

The point is that you need to know what your velocity was before the collision happened.

cobalt dune
#

What algorithms can I use to build a navmesh on a closed surface (for example: sphere) ? Tetraedalization is not very suitable due to extra edges, BPA is not entirely accurate...

unkempt zenith
#

Is there a pattern for when a value is managed by different contexts?
For example, player movement being restricted when a UI menu is open, but then it shouldn't allow it if it wasn't allowed before. Not sure if you get what I mean.

another example would be altering the game's time scale

hidden flicker
#

how do i snap a capsule collider to the ground?

autumn field
tardy path
#

I've been prototyping a platformer game lately, in which I want to have certain surfaces (the blue ones) be like normal solid surfaces, but some others (the purple ones), be bouncy, and while I managed to make a bouncy material that works very well when bouncing off the ground and ceilings, it doesn't really work against walls, and I'm not sure why or how to fix it

#

does anyone know how to fix it? feel free to ping me with responses or further questions about other factors at any time

#

Ive been thinking to make a check similar to a ground check but for wall collisions and a bounce tag, but I'm not sure if a simpler, more elegant solution exists

reef garnet
#

I've been buried in the docs but can't find anything, is there a built in method to get the distance between knots on a spline? I know there's a method to get the length of the whole spline?

strange cargo
#

If you don't need it at run-time, you're getting kind of close with the screen shots you posted. Double your button bindings so the action contains both WASD and arrow keys. Then click on a binding to change what controlScheme that button set belongs to using the properties on the right side.

soft shard
# tardy path Ive been thinking to make a check similar to a ground check but for wall collisi...

Its possible your movement logic could be overriding horizontal physics and gravity, you could try testing with a rigidbody that has no logic or try rotating the walls "forward" - I think a raycast approach from your player is fine too, though I personally wouldnt use a tag, I would use a inherited class (or interface) instead or something dynamic and descriptive about the object like a material, that way you could swap the script or material to get different effects for different surfaces, in case you may want more than just a bounce later

reef garnet
#

I'm using this to calculate the resolution for mesh generation along the curve and in some cases I want that between two knots on the spline

cosmic rain
heady iris
reef garnet
#

yeah I've found this function GetCurveLength(int) which can get the length from one knot to the next so I can sum the lengths between knots

heady iris
#

So you can convert from knot index to actual distance

heady iris
#

(if you care about that)

#

Non-uniform scale would be...interesting

reef garnet
#

nah I'm leaving the spline container at the origin so no need for transformation

heady iris
#

In that case, use Spline.ConvertIndexUnit to go from PathIndexUnit.Knot to PathIndexUnit.Distance

reef garnet
#

ok I'll check it out thanks

reef garnet
# heady iris In that case, use `Spline.ConvertIndexUnit` to go from `PathIndexUnit.Knot` to `...

Just for some added context since you seem to know splines well, this is the method I already have and am now refactoring to allow distance between knots

    public float GetSplineLength(int splineIndex)
    {
        return SplineContainer.Splines[splineIndex].GetLength();
    }
    
    public float GetLengthBetweenKnots(int splineIndex, int startIndex, int endIndex)
    {
        Spline spline = SplineContainer.Splines[splineIndex];
        
        // check if knot indexes are valid
        
        // Use GetCurveLength to get the length of each curve
        
        
        return spline.GetLength();
        
    }
    
    public int SampleSplineResolution(int index, float width)
    {
        float splineLength = GetSplineLength(index);
        int splineResolution = (int)(splineLength / width) - 1;

        return splineResolution;
    }```
#

any advice here?

heady iris
#

yeah, you can collapse this down to

#
var spline = SplineContainer.Splines[splineIndex];

float start = spline.ConvertIndexUnit(startIndex, PathIndexUnit.Knot, PathIndexUnit.Distance);
float end = spline.ConvertIndexUnit(endIndex, PathIndexUnit.Knot, PathIndexUnit.Distance);

return end - start;
#

I guess I'd allow start to be higher than end (by taking the absolute value of the result)

#

This will also allow for fractional indices

#

0.5 being 50% of the way between knot 0 and knot 1, for example

reef garnet
#

thanks

hazy pike
#

I have a problem where the raycast isnt hitting the object that I want it to hit. In the Editor I have an empty game object (supposed to be a machine) that has a couple of shapes as children to visualize it and each child has a box collider, one of the children objects is a console thats supposed to activate the machine. This empty game object has the script for the machine and has a rigidbody on it. I want the player to be able to interact with only the console and not the entire machine to get it working.

CraftingMachine:
public Transform console;

Player:

private void Update()
    {
        if (Physics.Raycast(playerCameraTransform.position, playerCameraTransform.forward, out RaycastHit raycastHit, interactDistance, interactLayerMask))
        {
            if (raycastHit.transform.TryGetComponent(out CraftingMachine craftingMachine))
            {
                if (raycastHit.transform == craftingMachine.console)
                {
                    Debug.Log("Console");

                    if (Input.GetKeyDown(KeyCode.E) && !craftingMachine.isJammed && !craftingMachine.isCrafting)
                    {
                        craftingMachine.NextBlueprint();
                    }
                } ```
cosmic rain
hazy pike
#

im guessing raycasts do not treat child objects independently?

cosmic rain
#

Share the updated code and the logs. As well as a screenshot of the hierarchy.

#

Raycasts don't have anything to do with child/parent objects. They hit what they hit.

#

They return info on the physical object that they hit. Note that having an rb somewhere in the parent, would make the parent the actual physical object, even if a collider exists somewhere in the children.

hazy pike
#
 if (raycastHit.transform.TryGetComponent(out CraftingMachine craftingMachine))
            {
                Debug.Log("looking at " + raycastHit.transform.name);

                if (raycastHit.transform == craftingMachine.console)
                {
                    Debug.Log("Looking at " + raycastHit.transform.name);

                    if (Input.GetKeyDown(KeyCode.E) && !craftingMachine.isJammed && !craftingMachine.isCrafting)
                    {
                        craftingMachine.NextBlueprint();
                    }
                }
hazy pike
cosmic rain
hazy pike
cosmic rain
spiral ibex
#

Either Unity's API for ECS is beyond garbage or I'm dumb. How am I supposed to query for reference type managed components in systems? Or should I open a topic in #1062393052863414313 which seems overkill.

oblique spoke
spiral ibex
pearl burrow
#

Hi. I have a class that on startup calls a method of all the interfaces of a type present in the scene (a load system)

something like

GameData gameData;
List<ISaveable> objects = new ();

foreach(var obj in objects){
  obj.Load(gameData)
}

and then when i quit the game, in the same way i call obj.Save(ref gameData), giving a ref so that i change the object passed.
Im wondering if its overkill to pass as ref in the Load method so that every change made at runtime are already in the class.
I ve come up with this problem because i have a skill system that holds info of only the levels of the skill. the level is multiplied by a constant to determine its power.
For example i have energy in the game starting at 100. Every levels i put in the "Energy skill" must increase the energy by 20 (and display it in the UI).

#

or maybe every class that have the Load method will have their copies of the gamedata (or datas into it) so that when the game is playing everything is updated within the game and only saved at the end. In this way i can just access these copies (which are updated and will be saved)

cosmic rain
pearl burrow
#

i think i replied myself while writing. But for clarification i need a way to update the values that will be saved (with autosave and or on quit).

#

so just holding a copy of the savedata (using the same classes) and calling some events when a value is updated is my go to

#

something like
GameData
PlayerData
SkillsData

then the playermanager manages the playerdata info, and listen to an event in skillsdata for when one of the skill is updated

cosmic rain
#

Yeah, I'd have separate data structures for save data and actual data used at runtime. And only create the save data structure during saving/loading.

steady moat
#

Terrible practice.

Player Prefs are actually registry entry.

steady moat
#

Kinda obvious isnt ?

#

File, like all other games that has been created since the dawn of time.

#

Whatever format you want, wherever you want.

#

I prefer json in Application.persistentDataPath

#

But, depending on the console, Switch, Ps or Xbox I use other means.

pearl burrow
steady moat
#

I mean, you kinda have to use other means.

steady moat
#

Whenever you want to save, you generate a XSaveData.
Whenever you want to load, you read from the save as a XSaveData and then interpret the data/load.

#

Obviously, the save data and the state of the object you want to save will have a lot in common. There is a lot of library that enables you to configure the state to automatically handle the "translation" part (meaning that you only needs the actual runtime representation).

#

However, it usually harder to make it works correctly.

pearl burrow
steady moat
#

Yes, it does. But not because you have a lot of data but because you use PlayerPrefs + you are not serializing anything.

#

Also, is there a reason why everything has the "_player" prefix ?

steady moat
# pearl burrow so the managers update the copies of the save data and fire the events/edit the ...

Exactly, the save data should only be treated as a DTO. https://en.wikipedia.org/wiki/Data_transfer_object

In the field of programming a data transfer object (DTO) is an object that carries data between processes. The motivation for its use is that communication between processes is usually done resorting to remote interfaces (e.g., web services), where each call is an expensive operation. Because the majority of the cost of each call is related to t...

steady moat
#

There is many things that are wrong in your code...

#

I do not even know what to say

#

Obviously not lol.

#

Like why is it static ?

#

Why are you not using [SerializedField]

#

Why do you have your default into the constructor

#

Why is there any business logic there if it is suppose to be the save

#

Why the event are static

#

Why the experience table is directly associate to the player ?

#

Take all of and directly shoot them in your character:

    [SerializeField] private string _playerName;
    [Header("Statistics")]
    [SerializeField] private int _playerLevel;
    [SerializeField] private int _playerHealth;
    [SerializeField] private int _playerMaxHealth;
    [SerializeField] private int _playerMana;
    [SerializeField] private int _playerMaxMana;
    [SerializeField] private int _playerExperience;
    [SerializeField] private int _playerMinAttack;
    [SerializeField] private int _playerMaxAttack;
    [SerializeField] private float _playerHealthRegen;
    [SerializeField] private float _playerCritRate;
    [SerializeField] private float _playerCritDamage;
    [SerializeField] private int _playerStatPts;
    [SerializeField] private int _playerSkillPts;
    [SerializeField] private int _playerStrength;
    [SerializeField] private int _playerAgility;
    [SerializeField] private int _playerIntelligence;
    [SerializeField] private int _playerConstitution;
    [SerializeField] private int _playerAccuracy;
#

After, take time to search on how to save data.

#

Yeah, which means that you can only have 1 character ?

#

Yeah, and that is an issue.

#

Which you would almost definitely need to solve down the line.

#

Yeah, that makes your code garbage.

#

Hey, you are the one that asked.

clear vapor
#

@modern atlas

#

the code just reads what was sent and dmages the enemy accordingly

modern atlas
#

Have you tried debug logs/break points (if using VS) to see which one gets called when your RB goes flying?

clear vapor
#

and it just calls the hit detect one and does nothing

#

Currently they try to mimic the body but also don't a sec

#

they were workigna dn sticking to the body before but when I added these extra rigid bodies they flew away

modern atlas
#

So which segment of your code is responsible for the issue?

clear vapor
#

None?

modern atlas
#

And explain your set up a bit more

clear vapor
#

Ok so I just have rigid bodies on the same elemt that has the collision detectors

modern atlas
clear vapor
#

I didnt I was proving it wasnt

#

My bad for the confusion but

#

wacky

modern atlas
#

Not a code related statement.

clear vapor
#

ANd now its detecting collision

#

I decided to reset the untiy enginge I guess that fixed it?

modern atlas
#

Not sure, did it?

clear vapor
#

it just works

#

I have been making all sorts of magic occur

clear vapor
#

If you would care

modern atlas
#

Sure? Ask away

clear vapor
#

due to it have collision detects that would get overwirtten during ther agdool creation process

#

I have made a spare ragdoll and my goal is to have that ragdooll spawn in the same state as the enemy as the enemy is destroyed when it dies

#

I mainly wonder if there is an easy way to transferbone data from the live enemy to tha ragdoll model

modern atlas
#

So it spawns in the same position where the enemy dies in? If i’m understanding that right.

#

Or it’s data/status?

clear vapor
#

I rather it not die and tpose is spawned in

modern atlas
#

No other purpose that I know of. Main reason is simply for convenience for private members to avoid naming conflicts within other scripts of the same namespace

clear vapor
modern atlas
modern atlas
#

Pretty sure that guy got banned due to his insolence lol

clear vapor
#

Joyrine mianly how do i copy over the rig data effieciently?

modern atlas
#

You would just take the transform.position that was captured at death and apply it to your ragdoll script. You’d likely want to reference the class where you instantiate the object

#

All dynamically of course

clear vapor
#

I dont have a rig body and it working? I am incredibly confsued if I add rig body it breaks the hit detection

#

BuT more improtnatly it t-poses on death

modern atlas
#

Pretty sure you’d want to declare a variable of type vector3 globally then assign that variable to the object you want to destroy followed by .transform.position

clear vapor
#

how would I transfer the velocity?

#

Cause I do not have a rig body on it

#

The nav mesh agent handles the moving fine I guess

modern atlas
#

I think you would find your object of type Rigidbody and similarly to position logic, but store the .velocity?

clear vapor
modern atlas
#

Well how will you transfer velocity then?

clear vapor
#

Which I do not understand

modern atlas
#

You can’t really work with physics without a rigidbody then

clear vapor
modern atlas
#

Then my point still applies. You’d find the object of type NavMeshAgent and store it’s .velocity

clear vapor
#

Would I be able to just give a vleocity and a direction or is it more complicated than that?

modern atlas
#

It’s pretty straightforward

#

Unless you’re looking for more complex forces such as certain trajectories

clear vapor
#

Last thing to deal with is the rig data

#

SO the ragdoll doesnt just tpose and face plant

modern atlas
#

Good luck!

pearl burrow
#
[Serializable]
public class Test {
  [SerializeField] private int myInt = 0;
  [SerializeField] private Dictionary<MyEnum, Dictionary<string,string>> myDict1;
  public Dictionary<MyEnum, Dictionary<string, string>> myDict2;

  //constructor
}

why myInt and myDict2 are saved into a json while myDict1 is not?

#

enums must be set to serializable too?

cosmic rain
#

MyDict2 shouldn't be saving either. You must be confusing something

pearl burrow
#

im using newtonsoft to serialize and deserialize in json

#

and they save

cosmic rain
#

Okay. Then I'm not sure.

#

I don't know if it requires the SerializeField attribute or not, but maybe that's the issue?

pearl burrow
#

you mean i make it private without using the serializefield

#

i try and tell you

cosmic rain
pearl burrow
#

also mydict2 is

pearl burrow
#

and gets serialize thats why im confused

cosmic rain
pearl burrow
#

but i also have another class that has private [serializefield] but simple integers and gets serialized

#

i guess he doesnt like private dictionaries? XD

#

removing the serializefield doesnt work either if its private

#

yeah insane, he just doesnt like private dictionaries (idk about other data structure). Making it public save it properly

clear vapor
#

it just works

cosmic rain
pearl burrow
#

well i dont know why it doesnt

cosmic rain
#

Can't say much about newtonsoft serializer. Maybe check the documentation.

dusk apex
# clear vapor

Random refactoring to reduce unnecessary getchild calls and limit iteration if one has fewer children than the other: ```cs
public void CopyRig(Transform spinin, Transform ragger)
{
int spiCap = spinin.childCount;
int ragCap = ragger.childCount;
int cap = spiCap < ragCap ? spiCap : ragCap;

for (int i = 0; i < cap; ++i)
{
    Transform child = ragger.GetChild(i);
    if (child.CompareTag("ragdoll")
    {
        Transform other = spinin.GetChild(i);
        child.position = other.position;
        child.rotation = other.rotation;
        CopyRig(child, other); 
    }
}

}```

swift falcon
#

!collab

tawny elkBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
Collaboration & Jobs

plain plaza
#

Hey guys, I've been struggling with this for a while, and I don't know where to ask. So i've made a chatgpt wrapper using unity and tried to export it to WebGl, but I keep getting a webassembly error. I'm pretty sure I can find another way to do the wrapper. I'm just wondering what went wrong and why it's broken, anyways it works fine and is able to be build in Windows.

cyan ivy
plain plaza
#

oh alrighty

stiff wasp
#

Code Review - Settings Script

hardy pasture
#

My PlayerInputActions are setup like this:

#

Then I have a PlayerInputLogger prefab with a PlayerInput component using my PlayerInputActions asset and my PlayerInputLogger component:

#

Here's the code for PlayerInputLogger component:

public class PlayerInputsLogger : MonoBehaviour {
    public InputActionReference Action1;
    
    void Start() {
        Action1.action.performed += _ => Debug.Log("Action 1 performed");
    }
}
#

Then, I have PlayerInputsSpawner object and the component in the test scene. Here's the code for PlayerInputsSpawner component:

public class PlayerInputsSpawner : MonoBehaviour {
    public GameObject PlayerInputLogger;

    void Start() {
        PlayerInput Player1 = PlayerInput.Instantiate(PlayerInputLogger, controlScheme: "KeyboardP1", pairWithDevice: Keyboard.current);
        PlayerInput Player2 = PlayerInput.Instantiate(PlayerInputLogger, controlScheme: "KeyboardP2", pairWithDevice: Keyboard.current);
    }
}
#

When I start the game, here's how the scene looks like:

#

It logs only when I press on the G key and not Numpad1 key

#

When I switch the control schemes on the spawned objects, it logs when I press numpad1 key but not the G key

#

Only the first instantiated object is working.

prisma hatch
#

Hi lads, I have a question,
Suppose my game is capped at 60 and only 60 fps and by capped I mean it always set the fps to 60
What happens if a machine that runs my game can only run it at flawless 5 fps?

leaden solstice
#

Then you get 5 fps

prisma hatch
#

Words, but I have a line that will cause the application to set the fps at only 60 every frame update

#

Then its still at 5?

leaden solstice
#

Capping is maximum

#

The closest you get is fixed update which can run multiple time on single frame

#

Even then you can’t get 60, obviously when your machine cannot keep it up

prisma hatch
#

I see

#

thanks a lot mate

errant raven
#

Has anyone worked with ML-Agents in Unity?

hardy pasture
#

Heck, you can code it so it runs faster at lower FPS

plain trail
#

i just dont get how its not

#

like i deont get the error

#

i baked the navmesh

knotty sun
#

That has nothing to do with NavMesh Baking. It's the Vector3 you are using to place the gameobject with the NavMeshAgent

plain trail
#

ok how do i fix

knotty sun
#

you debug the vector3 you are using

#

then fix it

thin aurora
errant raven
short osprey
#

Hi all. I’m trying to make an avatar customisation window. Ive made a scriptable object for clothing items where their type (head,chest,legs,feet) are set as well as a name and sprite. Several clothing items exist as assets now.

Im trying to find out the best way to make my customisation window show them all once. The idea is that by clicking on them in the window, the avatar will equip them. That i can code fine though. Im trying to find out how to show them all.

Best I can find is ScriptableObject.CreateInstance<T> but this seems more usable for dynamically generating new clothing items to exist in the game, rather than load existing assets in. Any advice?

steady bobcat
thin aurora
modern creek
knotty sun
short osprey
modern creek
steady bobcat
short osprey
modern creek
#
public class InventoryItem : MonoBehaviour
{
  [SerializeField] private Image ItemIcon;
  .. methods, fields, properties, whatever ...
}

public class InventoryItemDatabase : ScriptableObject
{
  [SerializeField] private InventoryItem SomeItem;
  ... x 1000 ...
  public InventoryItem GetItem(int itemId) => .. lookup table or whatever to return the right item ...
  
}```
#

then, say you have something that needs access to the item database..

short osprey
#

So you’d say make a component with a serialized InvdntoryItem array and manually drag all the assets in?

steady bobcat
#

that works just fine

modern creek
#
public class ItemDialogBox : MonoBehaviour
{
  [SerializeField] private InventoryItemDatabase ItemDatabase;

  public void OnOpenInventoryClicked()
  {
      int theItemId = ...;
      DisplayedItem.sprite = ItemDatabase.GetItem(theItemId).ItemIcon.sprite;
      DisplayedItemDetailsText.text = ItemDatabase.GetItem(theItemId).DetailsText; // or whatever
  }
}
short osprey
#

I think I see what youre going for

#

Makes sense

modern creek
#

Wherever you'd have a script that needs access to c# items (and unity items - like image/sound assets) - you can hold those in a scriptable object "database" and then just link the database to the script that needs it

#

you could even make SOs of SOs - which i might suggest for your situation

#

like an "item database'" SO that holds all the individual items as their own SOs

steady bobcat
#

its a good approach, id do something like make a Dictionary of them on Awake() to make look up quicker.

modern creek
#

I have my "crew database" which has references to all the (65!) crew in our game, and each crew SO has the artwork for all of the various poses and whatnot.. for inventory you could have weapon stats, weight, whatever

#

then i just link the crew database in whatever script needs access to deets about the crew (including "parent level" stuff like various art for each of the kinds of crew - like header images, ribbons, banners, etc)

#

hope that helps

steady bobcat
#

oh god why are there 65 seperate fields 😐

short osprey
#

Or can dictionaries be serialized with a customisabke key field?

#

I actusllt dont know

modern creek
#

(our poor artist had to draw 9-15 poses for each of those crew btw)

#

and our poor animator had to do 5-10 spine animations for them :p

steady bobcat
modern creek
#

So just bear in mind that resources and the resources directory will have some ramifications you may not be aware of

steady bobcat
modern creek
#

(in general I advise all new people to unity to avoid it because unless you're doing something advanced, it's probably not the solution you're wanting)

steady bobcat
#

Yea i work with Addressables only now but where i work we have a json -> protobuf config where we configure things and we configure addresses in there.

modern creek
#

Yep, that'd be a usecase- although I thought protobuf had a cpp option (like MessagePack)

short osprey
#

I appreciate the help, let me see what I can work out. I needed this nudge in the right direction, thanks!

modern creek
#

but config files and other runtime stuff might still be better accessed in the application directory api - not the resources directory

steady bobcat
modern creek
steady bobcat
modern creek
#

Sure and when we delete a crew?

#

Oops, everything in the game broke

steady bobcat
#

if each scriptable object has its unique id configured on it then there is no problem. And when i say "index" i dont specifically mean array/list index

modern creek
#

Oh, I see what you mean, like a list of them, then each SO has an enum with their ID, and I iterate the entire list (or build a dict lookup at startup) when I want to find one

#

sure, that's an idea, too, although we'd have to do some data validation on load (ie, make sure there's no dupes, that there's one for every enum expected, etc) but that's NBD

steady bobcat
#

That's true but you can always use OnValidate() to catch this in edit mode.

modern creek
#

yep, I like the idea, although ultimately we'd still have to define the value of each crew's identifier in the SO

#

so whether or not the "database" has 65 fields that have to be linked, or each of 65 separate crew SOs have an enum that's set one by one in the inspector is sort of irrelevant

#

I'll put it this way.. either way, it's a butt ton of linking textures/sfx/data in the inspector

#

I still haven't found a nice way to automate it

cold parrot
modern creek
#

Oh, I haven't.. I haven't touched that database code in a while, I rather like it the way it is (I also have messagepack and json serialization concerns)

cold parrot
#

your design has 65 well defined entities, its fine do handle that exactly like you did

#

you aren't making a library

#

reminds me of this meme

for (int i = 1, i < 4, i++) {
    printf("This is item {0}", i);
}

// vs

printf("This is item 1");
printf("This is item 2");
printf("This is item 3");
modern creek
#

or that chess one i see pop up all the time

knotty sun
modern creek
#

what? it's beautiful

#

🙂

knotty sun
#

Someone has never heard of Arrays or how to use them, lol

modern creek
thin aurora
knotty sun
cold parrot
#

one should not loose sight of what purpose programming serves in the end

knotty sun
cosmic rain
#

one should never lose sight of who he serves

thin aurora
modern creek
#

One should never lose sight.

#

(coming from a dude who is starting to get as old as @knotty sun and has to wear glasses)

#

❤️ steve

thin aurora
#

Woah, am I witnessing the birth of a friendship?

#

Typing is hard

knotty sun
#

and guess what, 50 years of staring at screens and I still don't need spectacles

modern creek
#

oh we go way back, although get as old as steve and i and "way back" can mean different things

#

but you use the word "spectacles", your argument is invalid

#

/me says, squinting at the screen through spectacles

knotty sun
#

so fault me for my enhanced vocabulary, thanks

modern creek
#

Just teasing. 🙂 Bed for me! gn

knotty sun
#

whilst we are on a related subject, wouldn't it be nice if people actually used the spelling checker that I know they have access to?

thin aurora
#

You're not fooling anybody

cold parrot
#

thay would not care

knotty sun
cold parrot
#

you need no spell checker if you can spell yourself

#

wouldn't that be nice

knotty sun
#

which, unfortunately, you obviously cannot

cold parrot
#

its interesting how you manage to remind me within 2 messages why i don't talk to you.

knotty sun
#

your loss, do you really expect me not to take a cheap shot when you set it up so nicely?

charred pivot
#

Why is x86 a checkbox, but x64 a dropdown?

dusk apex
knotty sun
#

x64 is an architecture implemented by different hardware manufacturers

dusk apex
#

Where they're implying that you're not allowed to select x64, ARM64 and Any CPU (all together) at any one given time.

charred pivot
#

IE. if I only have x86 checked, but CPU None checked, will it still be built if I build to Intel32?

steady bobcat
#

well x86 (32 bit) works in x64 just fine but its a bit weird why the plugin settings is like that

knotty sun
charred pivot
#

I guess I don't plan to build for 32 bit systems anyways, steam hardware survey doesn't even have any 32 bit OSes

knotty sun
charred pivot
#

I'll just delete the x86 dll and let it be

steady bobcat
#

if its x86 (32 bit) its gonna work if you will only target x86_64 (probably)
may be that it has to match so ignore me

charred pivot
#

I assume for that I'd have to mark it as both x86 and CPU set to 64, given both are in the name

#

whatever, I'll just pretend 32bit doesn't exist 🙈 🙉 🙊

steady bobcat
#

x86 is the instruction set, x86_64 is the 64 bit extensions added by amd making it support 64 bit os's

knotty sun
steady bobcat
charred pivot
#

Hmn, there's no scripting define symbols for ARM64 vs Intel64

knotty sun
heady iris
#

I suppose you could be trying to use intrinsics

#

I've thought about using POPCNT once or twice

charred pivot
#

But I think I can assume whichever dll is the correct one is in root for builds

#

It's not really well-documented

knotty sun
charred pivot
knotty sun
charred pivot
knotty sun
charred pivot
#

Yeah, was the full asset path

#

so just right clicking the correct dll and choosing copy path worked

wheat spruce
#

is there some way to move all the preferences from visual studio, over to visual studio code? VS works really well for me, lots of really good hotkeys and I have the editor settings how I like, and I dont know how to get VScode feeling good to work in

knotty sun
bleak garden
knotty sun
wheat spruce
knotty sun
bleak garden
bleak garden
knotty sun
wheat spruce
#

only time ive had weirdness is when I give my class a name that already exists in the UnityEngine namespace

#

but its easy to fix by just specifying "using foo as mything.foo" or whatever it is you do

chilly surge
#

Other than that, not sure what other VS preferences that you are referring to.

alpine jetty
knotty sun
alpine jetty
# knotty sun turn the crap off, problem solved

intellisense or the AI assistant that helps me refactor code super quickly and thus has made my code cleaner than its ever been? I don't want to turn off either they're really useful to me. Ctrl+z is a super familiar keystroke

knotty sun
bleak garden
alpine jetty
#

I have time now, I do the ideal design, that's pretty cool.

naive swallow
alpine jetty
heady iris
#

I found "intellicode" to be largely pointless

#

It was simply a bad idea generator

naive swallow
knotty sun
short osprey
#

@steady bobcat @modern creek

Hi again, I'm back with an issue regarding the clothing UI we discussed (using Scriptable Objects). The first script correctly loads the objects from the resources folder, but then when the second script tries to render them in a prefab to add to a scrollview, it results in a NullReference? I'm very confused why

[CreateAssetMenu(fileName = "clothingSerializedDB", menuName = "Serialization Source")]
public class ClothingSerializedDB : ScriptableObject
{
    private const string RESOURCE_PATH = "Clothing/Items";
    [SerializeField] private ClothingItem[] items;
    private IDictionary<string, ClothingItem> clothing;


    void Init()
    {
        ICollection<ClothingItem> resources = Resources.LoadAll<ClothingItem>(RESOURCE_PATH);
        clothing = new Dictionary<string, ClothingItem>(resources.Count);
        Debug.Log($"Returned {resources.Count} items");
        foreach (ClothingItem item in resources)
        {
            clothing.Add(item.ItemName, item);
        }

        //foreach (var item in items)
        //{
        //    clothing.Add(item.ItemName, item);
        //}
    }

    public ClothingItem this[string key] => clothing[key];

    public ICollection<ClothingItem> GetAll()
    {
        if(clothing == null)
        {
            Init();
        }
        return clothing.Values.ToArray();
    }

    public ICollection<ClothingItem> GetAll(ClothingType type)
    {
        if(clothing == null)
        {
            Init();
        }
        return clothing.Values.Where(item => item.Type == type).ToArray();
    }
}
#
public class DisplayClothingHandler : MonoBehaviour
{
    [SerializeField] private ClothingSerializedDB _clothingSerializedDB;
    [SerializeField] private GameObject clothingContainer;
    [SerializeField] private Transform content;

    public ClothingSerializedDB ClothingSerializedDB => _clothingSerializedDB;

    // Start is called before the first frame update
    void Start()
    {
        ClothingUI.NewClothingSelected += HandleNewClothing;
        Populate(_clothingSerializedDB.GetAll());
    }
    private void OnDestroy()
    {
        ClothingUI.NewClothingSelected -= HandleNewClothing;
    }

    void Populate(IEnumerable<ClothingItem> clothingItems)
    {
        foreach(ClothingItem item in clothingItems)
        {
            GameObject newItemClothingBox = Instantiate(clothingContainer, content);
            ClothingBoxRenderer renderer = newItemClothingBox.GetComponent<ClothingBoxRenderer>();
            renderer.SetItem(item);
        }
    }

    void HandleNewClothing(ClothingItem item)
    {

    }
}
bleak garden
alpine jetty
#

for me intellisense is about 3 things really:

  1. when I type "object." I see all its functions, fields, properties, and events
  2. F2 to rename a symbol all over the project
  3. Right clicking a class and having it shove it in its own named file
short osprey
#

the issue is the renderer.SetItem() line

heady iris
bleak garden
#

this server is not beating the allegations if this is how regulars talk to people

knotty sun
short osprey
#

professionals refactor regularly and design code in a way it can easily be

alpine jetty
#

hey can y'all both chill someone needs help

bleak garden
#

do you even hear yourself

alpine jetty
#

@short osprey reading now

short osprey
heady iris
#

Notably, your prefab is referenced as a GameObject. You could have assigned any object into that field.

alpine jetty
#

👆

heady iris
short osprey
#

it has the correcrt value

heady iris
#

so it working correctly doesn't guarantee much of anything

alpine jetty
#

does that gameobject have the ClothingBoxRenderer component though?

#

DIRECTLY on it?

#

(not on a child object)

steady bobcat
naive swallow
short osprey
short osprey
heady iris
#

I presume ClothingBoxRenderer is a component that handles displaying an item

#

(This is a good idea)

short osprey
#

yes its 1 box for 1 item

heady iris
#

At that point, you should just reference the prefab as a ClothingBoxRenderer 😉

short osprey
#
public class ClothingBoxRenderer : MonoBehaviour
{
    [Header("UI")]
    [SerializeField] private Image icon;
    [SerializeField] private TextMeshProUGUI text;

    public ClothingItem Content { get; private set; }

    public void SetItem(ClothingItem item)
    {
        icon.sprite = item.InventoryIcon;
        text.text = item.ItemName;
        Content = item;
    }
}
bleak garden
alpine jetty
naive swallow
alpine jetty
short osprey
#

I see the issue

steady bobcat
#

Haha well easy fix

heady iris
#

That's why you should reference prefabs by a specific type!

short osprey
#

yeah - my bad

heady iris
#

It'll prevent this from happening in the first place

#

I almost never reference prefabs as a GameObject

steady bobcat
#

Yep best choice if the component is on the root

short osprey
#

probably a good idea

alpine jetty
heady iris
#
[SerializeField] ClothingBoxRenderer prefab;
alpine jetty
#

I swear at some point unity would just instantiate it regardless but lately it doesn't like instantiating non gameobject types directly

short osprey
#

thats what i was going for actually

heady iris
knotty sun
heady iris
#

You can instantiate any Unity object type, including any kind of Component

lusty obsidian
#

There's a version of Instantiate with a generic type parameter that returns you the component

heady iris
#

yes -- so this works:

[SerializeField] Foo prefab;

void Start() {
  Foo instance = Instantiate(prefab);
}
alpine jetty
alpine jetty
#

at some point there was a change, if it's back in unity 6 that's great

heady iris
#

It has worked this way more-or-less forever

bleak garden
alpine jetty
#

I don't have one but here's what I can say is that I always did it exactly how you're showing. Then I worked on a game and one of the other devs was like "Well you can't just instantiate from the component type" and I was like "what? I absolutely can that's how I always do it". Then we tried it and he was damn sure right, Unity wanted me to instantiate the gameobject then grab the component

steady bobcat
#

Addressables does force you to use Game object only annoyingly.
Also wtf is this dumb other convo

heady iris
#
[SerializeField] GameObject prefab;

void Start() {
  Foo instance = Instantiate(prefab); // compile error; types don't match
}
alpine jetty
#

What do you mean? It was a serialized SomeOtherClass prefab being instantiated without .gameObject or .GetComponent is what I'm saying

short osprey
#

okay so it renders now, but.. what?

heady iris
short osprey
#

yep, ill try to solve it and otherwise go there. thx for the help so far

alpine jetty
#
[SerializeField] GameObject prefab;

void Start() {
  GameObject instance = Instantiate(prefab);
}```

^Obviously this works, we all know that

```cs
[SerializeField] SomeOtherMonobehaviour prefab;

void Start() {
  SomeOtherMonobehaviour instance = Instantiate(prefab);
}```

^ This would not work for me at a certain point, and very much to my surprise, I was eventually forced to do:

```cs
[SerializeField] SomeOtherMonobehaviour prefab;

void Start() {
  SomeOtherMonobehaviour instance = Instantiate(prefab.gameObject).GetComponent<SomeOtherMonobehaviour>();
}```
heady iris
#

The second one simply does not make any sense. That isn't how Unity's API has worked since at least vesrion 5.2 (the furthest back I could dig on the documentation site)

alpine jetty
#

oh sorry copied the wrong one (based that off your pasted example obviously)

heady iris
#

SomeOtherMonobehaviour is not actually a MonoBehaviour. There is no other explanation.

#

But even then, that wouldn't make any sense, because then GetComponent wouldn't work

alpine jetty
#

right

#

XD

heady iris
#

alterantively, you had two very similarly named types and got them mixed up

heady iris
alpine jetty
#

hmmm but then my getcomp would be null

#

it wouldn't fail but it wouldn't have been there

steady bobcat
#

Perhaps only the generic argument version can do this or was that just a quick example

alpine jetty
#

the code worked

heady iris
steady bobcat
#

DW I'm aware

alpine jetty
#

which again is something I considered XD this discord convo is like my exact pattern of conversation with myself AS this happened, that's why I can confirm like, this went down like I'm saying, this is all ringing bells I went through all of this like "I have always spawned these this way what on earth"

steady bobcat
#

Who knows 🤔
Go test now if you care but seems like a waste to wonder any more

alpine jetty
#

like trust me I would not do Instantiate(prefab.gameObject).GetComponent<MyType>() if I didn't have to, it's ugly haha

heady iris
#

There must some other missing context.

alpine jetty
#

yeah I think that's likely

steady bobcat
#

Interface? Its inconsistent where you can use one as a generic type arg for components

heady iris
#

An interface would not be serialized by Unity in the first place.

#

It would otherwise have been consistent with what you saw, though

steady bobcat
#

so quick to retort

heady iris
#

I've explored this a few times :p

steady bobcat
#

just a general idea. I often use Component ref and onvalidate to enforce interface implementation to do such references.

heady iris
alpine jetty
heady iris
#

If you had some other way of populating that field other than Unity serialization, this would've been possible

heady iris
steady bobcat
alpine jetty
heady iris
#

I was talking about rob's idea, yes

steady bobcat
#

i use this with OnValidate() to at least enforce interface implementation in edit mode

heady iris
#

with support for throwing in a GameObject (which'll give you its Transform) and getting the right component out, too

#

nice

alpine jetty
#

unless it's new in unity 6 you can't serialize interfaces to the inspector directly though unless I've lost my marbles

steady bobcat
#

as you can see, the non generic version works with an interface so that is useful.

heady iris
#

rob is serializing a Component

alpine jetty
#

oh! Okay good lord I understand the flow of the messages now haha yeah I'm with you

steady bobcat
#

👍

slow veldt
#

Does anybody know what I can use instead of PrefabUtility.UnpackPrefabInstance() since that function doesn't do anything anymore?
I have a prefab running in editor that creates children generatively in OnValidate and I don't need them flagged as prefab changes.

lapis otter
#

yyaa, pookies, How can i acheive this Squash, stretch effect via code,Also, that sweet lil tilt while falling in either direction?

#

Thanks in advancee!!

heady iris
hexed pecan
slow veldt
heady iris
hexed pecan
heady iris
#

this is in Unity 6

hexed pecan
#

Creating children in onvalidate sounds scary, yeah

#

Or unpacking a prefab

lapis otter
hexed pecan
#

I generally just avoid onvalidate alltogether

heady iris
#

Note: You should not use this callback to do other tasks such as create objects or call other non-thread-safe Unity API. You should only use it to validate the data that changed. This restriction is because OnValidate can be called often when the user interacts with an inspector in the Editor, and because OnValidate can be called from threads other than Unity's main thread, such as the loading thread.

hexed pecan
#

It runs very often

heady iris
#

Yeah, that's your problem for sure

hexed pecan
#

Also on assets

slow veldt
#

you are right i meant to type PrefabUtility.DisconnectPrefabInstance() hahaha my bad i pasted the wrong one

sudden inlet
#

yo guys, am stuck on slope mechanics for unity 3d cant get it to work as i want it to, can someone help?

hexed pecan
wintry crescent
#

Can I ask zenject-related questions here?

trim schooner
#

No

wintry crescent
#

where do I go then?

trim schooner
#

to the dev of whatever it is?

wintry crescent
#

I'd prefer to ask on a discord, as I feel like it's a silly question

heady iris
#

i mean, this seems like a unity-adjacent programming problem

wintry crescent
#

they don't have a discord

heady iris
#

The average person here is just much less likely to know about it

trim schooner
#

look through the issues on their github, may already be answered

wintry crescent
#

I just want to ask how a simple thing is done

heady iris
#

I do not use it, but I might have a clue anyway

trim schooner
#

the issues page on github isn't just for bugs no. Go see if your question has been answered there anyway

wintry crescent
#

I want to inject stuff into a non-monobehaviour class, when I make one, and I'm not sure how

hexed pecan
#

Why do people use zenject with unity, i'm genuinely ignorant about DI frameworks

wintry crescent
#

it helped me a lot in my previous project and got me my current job

hexed pecan
#

Can you give me an example use case?

wintry crescent
#

it's like singletons but better and cleaner and easier, and can inject scriptableObjects as well etc etc

#

that's the briefest description I could come up with

heady iris
#

it magically provides the correct object

sudden inlet
heady iris
#

singletons are an obvious example of DI where there is exactly one correct object

wintry crescent
heady iris
wintry crescent
#

I know how DI works in general, I'm ripping out our current homemade DI solution and replacing it with zenject

sudden inlet
#

i also tried this @hexed pecan

hexed pecan
#

@sudden inlet See !code how to post code properly

tawny elkBOT
hexed pecan
#

Maybe I should just go read on them

eager tundra
heady iris
#

It's an extremely broad concept

#

I would argue that this is DI:

public float Add(float x, float y) => x + y;
#

It has dependencies (some numbers) and you give it the dependencies

#

I will eventually stop being a stick in the mud and try out VContainer or something

sudden inlet
#
private void MyInput()
{
    horizontalInput = Input.GetAxisRaw("Horizontal");
    verticalInput = Input.GetAxisRaw("Vertical");
    if (Input.GetKey(jumpKey) && readyToJump && grounded)
    {
        readyToJump = true;
        Jump();
        Invoke(nameof(ResetJump), jumpCooldown);
    }
    if (Input.GetKey(jumpKey) && readyToJump && OnSlope())
    {
        readyToJump = false;
        Jump();
        Invoke(nameof(ResetJump), jumpCooldown);
    }
}

@hexed pecan

plucky karma
wintry crescent
hexed pecan
#

That's what confuses me, everything related to passing values around seems to to be DI

sudden inlet
wintry crescent
trim schooner
hexed pecan
# sudden inlet

So anything that is not absolutely pointing up is considered a slope here.
You should instead check the angle or dot product of the ground surface.
Like float slope = Vector3.Dot(slopeHit.normal, Vector3.up)
That would give you 1 on a perfectly level surface, and 0 on a 90 degree surface (and -1 on a ceiling)

wintry crescent
sudden inlet
#
private bool OnSlope()
{
    readyToJump = true;
    if (Physics.Raycast(transform.position, Vector3.down, out slopeHit, playerHeight / 3.5f + 0.3f))
    {
        if (slopeHit.normal != Vector3.up /*&& slopeHit.normal != Vector3.zero*/)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    return false;
}

this also doesnt work

wintry crescent
#

well, doesn't matter