#archived-code-general

1 messages · Page 185 of 1

heady iris
#

These can't be combined meaningfully. Bar | Baz is...just Buz

#
public enum MyEnum {
  Foo = 1,
  Bar = 2,
  Baz = 4,
  Buz = 8
}
#

In binary, a power of two is all zeroes, except for a single 1 somewhere

#

So Bar | Buz is 0010 | 0100, which is 0110

#

0110 is binary for the number 6

#

Note that there is no enum value with a value of 6

#

So, by default, you wouldn't see Bar, Buz or something

#

it'd just show up as an unknown enum value

#

The [Flags] attribute tells C# that you're combining enum values like this

#

When Unity sees an enum with that attribute, it gets displayed with that multi-select dropdown

#

rather than the default, which only lets you pick one enum value

tired elk
#

You may find examples that use bitshift too (1 << N, with N ranging from 0 to 31 i think). It's just another way to put the power of 2.

heady iris
heady iris
#

1 << id is a power of 2

#

1 << 0 == 1
1 << 1 == 2
1 << 2 == 4
etc.

#

int is a 32-bit number, so you can hold 32 different powers of two

#

(well, one will be a negative number, but whatever)

#

so, tl;dr, you should do two things here

#
  • assign a power of two to each enum value
  • use the [System.Flags] attribute
#

And if you want to manually add an "everything" enum, you could indeed do something like ~0

#

There will be an "Everything" option in the inspector if you serialize a field of that enum type

#

But you might want to be able to do that from code, too

#

var noFooPlease = MyEnum.Everything & ~MyEnum.Foo;

drifting root
#

Understood, thanks a lot

swift falcon
#

What's the easiest way to poll the actions using the new input system?

I tried doing this ```cs

//INPUT CONTROLS
public PlayerInputActions _playerControlls;
public InputAction _attack;
public InputAction _jump;
public InputAction _interact;
public InputAction _dodge;
public InputAction _stomp;
public InputAction _kick;

private void Awake()
{
    _playerControlls = new PlayerInputActions();
}

private void OnEnable()
{
    _attack = _playerControlls.PlayerMap.Attack;
    _attack.Enable();
    _jump = _playerControlls.PlayerMap.Jump;
    _jump.Enable();
}
private void OnDisable()
{
    _attack.Disable();
    _jump.Disable();
}```

But all it does is creates this list of actions on my script.
I assumed it would use the already predefined actions in the input actions list.

wintry crescent
#

If I have objects Parent and its child Child, both have colliders and both have scripts that detect collisions, but only parent has a rigidbody, why do collisions from both colliders go to the script on Parent, instead of the collisions on the collider of the Parent object going to Parent, and collisions on the collider of the Child object going to Child?

simple egret
#

_moveVector = context.ReadValue<Vector2>();

heady iris
#

You probably wanted an InputActionReference

#

This allows you to reference an input action from an input action asset

gray mural
#

How do I align this to left? There should be no spaces

public override void OnInspectorGUI()
{
    StretchablePanel script = (StretchablePanel)target;

    EditorGUILayout.BeginHorizontal();

    EditorGUIUtility.labelWidth = 50f;

    script.topStretch = EditorGUILayout.Toggle("Top", script.topStretch);
    script.bottomStretch = EditorGUILayout.Toggle("Bottom", script.bottomStretch);
    script.leftStretch = EditorGUILayout.Toggle("Left", script.leftStretch);
    script.rightStretch = EditorGUILayout.Toggle("Right", script.rightStretch);

    EditorGUILayout.EndHorizontal();

    EditorGUILayout.Space();

    //DrawDefaultInspector();

    if (GUI.changed)
        EditorUtility.SetDirty(script);
}
heady iris
#

If nothing actually enables that action, then you'd also want to enable it with moveAction.action.Enable();

#

In my game, I have a class whose sole job is to turn input action maps on and off

#

when you open the menu, it turns off the "gameplay" action map, for example

#

The PlayerInput component can also automatically do this for you. It will enable a single input action map automatically.

swift falcon
simple egret
#

Okay so there's .WasPressedThisFrame() on the action

#

It's like the old GetKeyDown

heady iris
#

Ah, yes, that's how you would poll the action

#

along with ReadValue to read the value if it's that kind of action

north cobalt
#

How can i make something like this or simlier to it
https://twitter.com/i/status/1680169229096476674

**This is the video showing the game main mechanic, The Player control the Character 1 (Angel) move to the door, Then replay (the same moves that player gave to the game (inputs) ), Now the player control Character 2 (devil) trying to kill the Character 1 (angel)

How can i save and replay the same Characters states on the game
**

For this #screenshotsaturday here's a simple trailer for my #gmtk2023 entry UVSU!

Do you understand what's going on in the game?

✨️I'm working on an expanded version of it, wishlist on Steam below! ✨️

Likes

410

▶ Play video
swift falcon
#

I was using this, but didn't seem to work.

heady iris
swift falcon
heady iris
#

so if you use a Vector2 move input and a button to jump, the list would store the move input at every tick, as well as whether or not you hit jump

#

note that this would require some determinism

#

a change in framerate could screw everything up

simple egret
#

It's like how Trackmania does it yeah, it replays input, instead of repositioning

heady iris
#

you could handle input and movement in FixedUpdate

simple egret
#

But yeah you cannot have randomness in the input processing in this case

rocky helm
#

Does TransformPoint/InverseTranformPoint use sqrt? Can't seem to find anything in the API.

heady iris
leaden ice
#

presumably it's just some matrix multiplication

simple egret
#

Source not available - it's extern so done on the C++ side

heady iris
simple egret
#

But yeah it would multiply the position with a matrix to transform to world space, and back to local space

rocky helm
simple egret
#

Matrix multiplication does not involve square roots

leaden ice
swift falcon
#

I added debugging log, doesn't seem to trigger for some reason.

leaden ice
#

so add more logs and find out why

rocky helm
#

due to loops

leaden ice
#

100 times per what

#

per frame?

heady iris
#

i think you should be more worried about the matrix math...

rocky helm
#

in 1 frame

leaden ice
#

the matrix math is almost certainly more expensive

#

it's many multiplication operations

simple egret
#

That's not a lot, 100 times per frame

swift falcon
simple egret
#

I thought you meant more like 10k

heady iris
rocky helm
leaden ice
heady iris
#

instead of the ones you copied into the input action field

simple egret
#

Optimize the really demending function then, not something else entirely

#

Spin up the profiler and see what uses the most resources

heady iris
#

optimization is not when you minimize the number of square roots

swift falcon
heady iris
#

use the profiler to identify hot spots. work on those

heady iris
swift falcon
#

I generated the class using this list

heady iris
#

right

#

PlayerInputActions

#

it contains all of your input actions, and I'm pretty sure it also enables them for you

swift falcon
#

So I don't need to enable them manually?

heady iris
#

my suggestion is to just log _playerControlls.PlayerMap.Jump.IsPressed()

#

I don't use the "generate C# class" option myself, so I'm a little unfamiliar

swift falcon
#

I see. I'll try that

heady iris
#

I wonder if the original Jump action is getting the inputs, and your new copy isn't

north cobalt
simple egret
# swift falcon I see. I'll try that

Usually when you tick the Generate class option, you create a new YourInputAsset(), enable it (or part of it), and subscribe to the events. All of it in the code, no drag-drop required

north cobalt
swift falcon
#

the controls for WASD movement work fine using the original, non-polling method

rocky helm
#

Would taking Input from the player in FixedUpdate be considered bad practice?

swift falcon
#

I just know that fixed update should be left for physics stuff

simple egret
#

It straight up wouldn't work in some cases

rocky helm
#

oh

simple egret
#

As FixedUpdate runs on a different interval, you can have skips in input especially when you use GetKeyDown or WasPressedThisFrame

north cobalt
simple egret
#

Because the timing not "aligned" with Update

#

By the time you pressed the key, the frame could have ended before FixedUpdate gets run, swallowing the input you made

heady iris
#

My thought is to read them in Update, and then apply them in FixedUpdate

#

Then just record the values you applied in each FixedUpdate cycle.

#

Then, to replay the player's actions, just consult that list in FixedUpdate

#

So you wouldn't actually record the player's inputs, per se

#

but rather than values you got based on the player's inputs

heady iris
#
public struct InputFrame {
  public Vector2 move;
  public bool jump;
  public bool shoot;
}
#

you'd record something like this

sweet egret
#

Does anyone here know how to set up IK for a rigged arm? I’ve tried so many tutorials and they all don’t make sense. I don’t know what poles and homes are or how to set them up. I have a rigged model all ready so if anyone can help, I’d be very thankful

placid island
#

Is it possible to copy a component from one game object and add that to another game object?

sweet egret
ashen yoke
sweet egret
#

True

ashen yoke
#

JsonUtility should work in some cases

#

for others only manual copy methods

placid island
ashen yoke
sweet egret
#

If it’s a set value, a prefab would keep it

#

However, if it’s a reference to a UI element or some gameobjects, they will not

#

But yes. .cache is right

ashen yoke
#

even without a prefab

#

you can just Instantiate an existing gameobject

placid island
#

But that component only should exists when the player enters an area, I want to dynamically add and remove it.

ashen yoke
#

which will do the copying for you

#

use a gameobject as a container for your component

#

even if its a single component, its fine

sweet egret
ashen yoke
#

you can remove

#

Destroy(comp)

sweet egret
#

Oh. I didn’t know that

ashen yoke
#

problem is recreating it afterwards

sweet egret
#

Lol. Thank you

placid island
#

Ah, I achieve that by disabling and enabling components.

#

Thank you

sweet egret
ashen yoke
#

barely touched mecanim ik, barely touched new rigging package

#

you have better luck in specialized channels

sweet egret
#

Aah ok. Thank you so much. I didn’t know where to look

drifting root
#

Hello, can anyone advice me how can I make my cylinder rotate depending on the terrain under it?
I tried to do this through the Raycasting down from the center of object, but it didn't work well, as while cylinder was near some terrain's roughness it was starting to rapidly rotate (because raycast takes not the nearest point of the terrain - screenshot should explain my idea here). So I tried to do that calculating the closest point, but it still doesn't work quite well, as you can see from the video
This is a DOTS project and I am not sure I can ask this question here, but there was no help from the #1062393052863414313 , so maybe I can ask for help here. If I still cannot, I am sorry for offtop in this channel

heady iris
#

it looks like your raycast is just going to the wrong place entirely

#

it may be starting underground

drifting root
#

Are you about the video?

heady iris
#

Yes. The video shows the cylinder mostly just standing straight up.

drifting root
#

There is no usual Raycast. In the video CalculateDistance is used, which is calculating the closest point of terrain to the given
If I am not mistaken I CalculateDistance (or Raycast in the first try) from the center of the bottom of the cylinder: it is 2 units high, and I CalculateDistance (Raycast) from the cylinderTransform.position.y - 1f with unchanged x and z coordinates

#

Script also puts the cylinder.y to the RaycastHit.position.y + 1

heady iris
#

ah, I see

drifting root
#

So the idea is to make cylinder stand on the terrain without gravity simulation (which is not needed)

heady iris
#

You can just do several raycasts to get an average surface normal.

ashen yoke
heady iris
#

that too -- I have never used it, but you should be able to ask it what the normal is

#

smearing that out over a few points will give you something less wobbly

ashen yoke
#

lots of utility there

#

im just sharing what i remember, may be inapplicable

drifting root
#

Okay, I will try to get use of it. Thanks

craggy lava
#

so this is my player movement script right now, and it has the problem of moving faster when moving diagonally
anybody have a recommendation for a better movement script?

heady iris
#

Vector3.ClampMagnitude is your friend

#

or Vector2, in this case

#

this shows the problem. it suggests normalizing the vector, which is also fine, although it'll mean you can't move slowly with a joystick

gray mural
#

it is possible to disable all mouse interactions for all scripts except of current?

#

I want mouse not to interact with my own scripts and UI Scrollbars when I am stretching my panel with StretchablePanel script using mouse

drifting root
heady iris
#

i wonder if you could just precompute a smoothed normal map

ashen yoke
heady iris
#

you'd make a 1024x1024 array of vectors, basically

gray mural
ashen yoke
#

transform.SetSiblingIndex(stretchablePanel.GetSiblingIndex()-1)

#

a transparent Image, that blocks all raycasts

gray mural
#

maybe I have to spawn transparent image under stretchablePanel?

ashen yoke
#

yes

#

thats what i do

#

not elegant, but works

drifting root
gray mural
ashen yoke
#

i can imagine you could - control all canvases raycast state

#

use/add EventSystem isolation contexts

gray mural
ashen yoke
#

i dont see anything of sorts in event system from a glance

#

but adding something like that should be trivial

#

i dont see how it should tank performance

cold parrot
#

is this an xyproblem maybe?

gray mural
ashen yoke
#

dont think so, pretty common thing

#

isolate ui elements from the background

gray mural
cold parrot
#

what about designing around a event system current object check?

gray mural
ashen yoke
#

you can directly modify event system if you drop it into the project

#

ugui is opensource

gray mural
ashen yoke
#

something like "if object is not part of the root set as isolation context, return"

#

it may be much simpler than that, i didnt delve into source

gray mural
#

oh, I have found it

#

I wonder why it's all grey

#

also I cannot edit it

oak sierra
#

Quick question... I have a script that generates noisemaps from a scriptable object. I'd like to bake these prior to runtime. Is there a system that I can leverage in unity to do this--or would I just be writing a on serialization hook to create an asset file?

cold parrot
tall pewter
#

Ok I understand your point and I respect your opinion, but I disagree with you, I have bought several assets and you are right that if some assets are not of good quality, but most of the assets are of very good quality, renowned games have used assets from Unity Asset Store, I consider it a good solution and it depends on the user if it suits their needs or not.

To be honest, some of the assets that I am currently using have saved me months of work because they simplify a complex task, then I have entered to see how its code is structured and it is more than enough to understand how the tool works and to be able to extend it to my liking .

Although from the beginning what I really wanted to know was which of the two assets that I mentioned could be more useful for my type of project, I appreciate your analysis of the asset store, but I will continue buying and supporting people who really help other developers to make your job more efficient. I myself have created tools for other languages in which I am a senior and have helped many people.

oak sierra
#

Right--I guess I'm wondering where the appropriate place to put that code would be. I could use ISerializationCallbackReceiver.OnBeforeSerialize() to bake. But I'd also want to find a solution to detect if the asset changed, so I'm not redundantly baking.

I'm wondering if there is some sort of prebuilt system for a baking step in Unity that I should be leveraging?

cold parrot
#

Most of the behavior assets in the store have missed (or never taken) the train that marries FSMs and BehaviorTrees, which is a necessary evolution for managing complexity. FSMs are great for transitions/cancellations/fallbacks, BTs for describing what happens over time.

#

Whichever path one takes, diy or library, good (practical) AI architecture takes a few iterations to get it right in your head.

thick terrace
oak sierra
#

@thick terrace This looks like it has potential--thank you!

green oyster
#

someone clarify

#

does it fully run the addnewstagepart code?

#

before moving onto the next method

#

or it will call that first method, and then move to next line, and call that one too

oak sierra
#

It will fully run AddNewStagePart--unless AddNewStagePart is a coroutine

green oyster
#

ok thanks

leaden ice
lavish ridge
#

Hey guys! I recently exported my game to Webgl, which works fine in the unity editor, and, when I load in to my scene, all I see is pink.

The console says that it couldn't find the shaded Unlit/Texture and that shader is null. What do I do?

undone mesa
#

Hi guys! I'm trying to apply a velocity to my bullet, but I can't understand how it works... Could someone explain to me? Thanks! 😄

My code:

bullet.GetComponent<Rigidbody>().velocity = Quaternion.AngleAxis(Random.Range(-3, 3), Vector3.up) * cam.transform.rotation.eulerAngles * bulletSpeed;
gray mural
#
private (Transform transform, int siblingIndex) activeUI;

//
Destroy(activeUI.transform.gameObject);

does it work this way or is it just a copy?

shell scarab
#

although that's a value type tuple you're making with the ()s

gray mural
#

Item1 is renamed to transform

#

and Item2 to siblingIndex

shell scarab
#

my bad, yea i works

shell scarab
#

TIL you can rename Item1 and Item2

quaint rock
#

yeah that will work and since its a value tuple everytime you reassing it, its a copy

shell scarab
gray mural
shell scarab
#

still points to the original game object

quaint rock
#

gameobject is a reference type the varaible for one, is just a pointer

#

a copy of a pointer, still points to the same object

shell scarab
#

also AFAIK it only copies the tuple if you pass it as a variable, they're passing the referenced gameobject

quaint rock
#

though if you are using these same 2 types grouped togeather often

#

i would be tempted to just write a named struct type for it

quaint rock
gray mural
#

thank u

quaint rock
#

anything that is a class is a reference type

#

primitives except for string and structs are value types

gray mural
#

oh, my bad, I have folgot that it doesn't depend on tuple

#

so if it was a struct, it wouldn't work

shell scarab
# undone mesa Hi guys! I'm trying to apply a velocity to my bullet, but I can't understand how...

well you're setting the velocity, not adding. But

Quaternion.AngleAxis(x, y) creates a rotation x angles around y axis, so you're rotating randomly between -3 and 3 around the Vector3.up axis.

then you're multiplying that quaternion by a vector which is the angles of the camera's rotation, which rotates that vector (not entirely sure why you're doing this, idk if that leads to a desired result)

then you're multiplying that vector by a presumably float that represents a speed

quaint rock
gray mural
#

struct isn't a reference type

#

it's a value type

quaint rock
#

since its a gameobject contained in it

#

both value tuple and struct are value types

gray mural
quaint rock
gray mural
#

I have messed up with a value and reference types even though I knew it

shell scarab
gray mural
#

I forgot that if tuple is a value type, it doesn't matter mean it stores copies of classes

#

it means tuple itself is a value type

quaint rock
#

good example of those behaviour is Vector3 if you do a.position = b.position assuming a and b are transforms. you are not making them both the exact same vector but just making a's position a copy of b's position

shell scarab
#

also the tuple itself will only copy if you try to assign another variable to that same tuple, such as passing it to a method

frosty surge
#

Does anybody know what is the correct way to make an android game automatically goes to pause screen when leaving the game in background then going back to it?

gray mural
quaint rock
#

like a reference is just a address really, like the address of my house is 42, say someone copies that number down somewhere else, well it still equals 42 and you could find my house with it

shell scarab
#

in the player settings

drifting root
#

Can someone please explain how Unity sets the pivot to come 3d object? As I understood, I cannot change the pivot and the only way is to create an empty parent object as a new pivot? Is it true? It seems to me a little dirty, when you need to change that pivot for hundreds of such objects (units in RTS)

drifting root
#

:(

heady iris
knotty sun
drifting root
heady iris
#

is the origin of these models not placed at the feet?

drifting root
shell scarab
#

(0, 0, 0) will be the origin unless changed in your modeling program

drifting root
heady iris
#

ah, then yes

#

You usually want to make the model a child of something else anyway, though

#
Unit
  - Model
  - SomeOtherThing
#

this makes it easier to replace models down the road, for example

shell scarab
#

if you're using unity's meshes, in your unit prefab make an empty parent and position the object accordingly

drifting root
heady iris
#

well, in this case, it'll let you offset the model correctly

shell scarab
#

also make sure this is set to pivot, top left of the editor window:

#

or else it would still select center of the cube if set to center (default) when moving things in unity

heady iris
#

note that this has no effect on how the game actually works. it just determines where your editor gizmo goes.

shell scarab
drifting root
#

Oh, maybe it is not the parent's position changes, but gizmo's position changes

#

But still parent's gizmo is glued to the camera from that moment for some reason. I thought it should be still in its own coordinates?

summer oar
#

Doing an optimization and refactoring pass over a fork of an old volumetric lighting technique for the built-in RP. Saw this code in it.

material.SetInt("_SampleCount", sampleCount);
material.SetVector("_NoiseVelocity", new Vector4(noiseVelocity.x, noiseVelocity.y) * noiseScale);
material.SetVector("_NoiseData", new Vector4(noiseScale, noiseIntensity, noiseIntensityOffset));
material.SetVector("_MieG", new Vector4(1 - (mieG * mieG), 1 + (mieG * mieG), 2 * mieG, 1.0f / (4.0f * Mathf.PI)));
material.SetVector("_VolumetricLight", new Vector4(scatteringCoef, extinctionCoef, light.range, 1.0f - skyboxExtinctionCoef));

Wondering if there's a speed benefit from switching to property IDs instead of property names, or if it's not worth doing so

heady iris
#

the gizmo will always be exactly at the position of the parent object

shell scarab
#

Clicking on the cube in the scene view would select the cube (the child), not the parent, so you'll still see the cube's pivot.

drifting root
#

Okay, got it
But one last question, which may be a little silly: why I cannot set different settings for child and parent? For example set pivot and global for the parent, but center and local for the child (as I understand Toggle Tool Handle Rotation's choice affects not the editor's gizmo, but how it rotates the object (around the parent if local and around its own center if global))

shell scarab
#

it's just changing where the pivot is displayed to you, it's not a gameobject setting

heady iris
#

as I said earlier, they do nothing to how the game works

drifting root
#

But when I change global to local, it change the way it rotates the object

heady iris
#

it changes how your editor gizmos work

shell scarab
#

yes, because you're rotating it on the global axis not the local axis

heady iris
#

I leave mine on Pivot and Local most of the game

shell scarab
#

same

heady iris
#

sometimes switching to Global

#

I do not like Center. It just confuses me most of the time

drifting root
#

Thanks a lot

gilded ocean
#

Hello can someone tell me a free way how to filter bad words in my game?

leaden ice
#

Turns out it's not an easy problem to solve

ember cape
#

How do you accomplish that because I am having a hard time figuring it out.
Basically what I have going on right now is my Bootstrap scene contains a listener for when scenes are loaded:

        private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
        {
            if (mode == LoadSceneMode.Additive)
            {
                foreach (GameObject gameObject in scene.GetRootGameObjects())
                {
                    //Debug.Log(gameObject.name);
                    if (gameObject.name == "xyz") do abc...
                }
            }
        }

And from there you loop through game objects and add the required references when need be?

green oyster
knotty sun
shell scarab
#

I do Object.FindObjectOfType

heady iris
heady iris
earnest gyro
#

what is new Vector3() without arguments? I'm trying to initialize a dictionary with values, but I want it to start "empty" and fill up as entities "learn" about the world. Currently I've got if _ant.Memory.nearestResource[ResourceType.Food] != null where _ant.Memory.nearestResource[ResourceType.Food] is initialized to new Vector3().

#

But I think it isn't working

earnest gyro
#

Bleh

leaden ice
#

Vector3 cannot be null

#

it is a struct

#

structs cannot be null

earnest gyro
#

Gotcha

shell scarab
leaden ice
#

there's no reason to put an empty/null value in

earnest gyro
#

I find ContainsKey a little ugly.

leaden ice
#

just make sure you use myDict.TryGetValue whenever you read it

#

don't use containsKey

#

use TryGetValue

earnest gyro
#

Is there a reason?

leaden ice
#

it's cleaner

#

and faster

earnest gyro
#

TryGet is an if and a get all in one?

leaden ice
#

yes

earnest gyro
#

How/why is it faster?

leaden ice
#
if (myDict.TryGetValue(key, out val)) {
  val.Whatever();
}
else {
  // not present
}```
#

it's faster because it doesn't duplicate the get operation / key check

earnest gyro
#

Ah, sure

#

Thanks!

leaden ice
#

compare this will the nullable solution:

var val = myDict[key];
if (val.HasValue) {
  val.Value.Whatever();
}
else {
  // not present
}```
Very similar I guess but using TryGet will be a memory savings in two ways:
- no use of memory before there's a value present
- the values will be smaller since they don't have the extra storage space associated with the nullable wrapper

Also the code is cleaner since you directly can work with the Vector3 instead of having to deal with the nullable
#

Just my $0.02

earnest gyro
#

Yeah I agree

#

Next question: this dictionary, nearestResource is meant to store the Vector3 of the nearest resource, indexed by the enum ResourceType. It's possible for the nearest resource to get depleted, in which case the nearest resource of that type shouldn't exist anymore. It'd be best, then, to just delete the key/value pair instead of nulling the value?

leaden ice
#

yes

earnest gyro
#

word

leaden ice
#

it's also not possible to null the value

#

😉

earnest gyro
#

that's what it sounds like lol

leaden ice
#

unless you're using a nullable type

#

but that's just kinda... asking for a memory leak tbh

ember cape
# shell scarab I do Object.FindObjectOfType

T Object The first active loaded object that matches the specified type. It returns null if no Object matches the type.
regardless of scenes?
Because I was under the impression that if I run that from a script in my main scene, I wouldn't be able to get stuff from my sub-scene(s)

heady iris
#

be careful with the phrasing here

#

"subscenes" are an ECS-specific concept

#

you're just doing additive scene loading, right?

ember cape
leaden ice
#

notice it's just a static method - The call is not actually associated with any particular object

heady iris
#

then yes, it searches everywhere

#

this came up yesterday

#

you might get punked if you run it before the other scenes finish loading

#

hey, small problem: I need to figure out the yaw and pitch that would give me a certain look vector

ember cape
shell scarab
heady iris
#

I guess I should project the vector onto two planes and calculate the angle between them and...

#

hm

#

yaw seems obvious: project onto the XZ plane and then get the signed angle between it and Vector3.forward

shell scarab
#

Yet another way to do it is to make the global manager a singleton and just reference the static instance in your scene managers

leaden ice
heady iris
#

gah, internet died

heady iris
leaden ice
#

not sure I follow

#

SignedAngle uses an axis parameter and the vectors are basically projected on that plane

heady iris
#

Oh, they do get projected?

shell scarab
heady iris
#

The angle returned is the angle of rotation from the first vector to the second, when treating these first two vector inputs as directions. These two vectors also define the plane of rotation, meaning they are parallel to the plane. This means the axis of rotation around which the angle is calculated is the cross product of the first and second vectors (and not the 3rd "axis" parameter).

#

dunno

leaden ice
#

e.g.

float yaw = Vector3.SignedAngle(Vector3.forward, lookVector, Vector3.up);
float pitch = Vector3.SignedAngle(Quaternion.AngleAxis(yaw, Vector3.up) * Vector3.forward, lookVector, Quaternion.AngleAxis(yaw, Vector3.up) * Vector3.right);```
heady iris
#

i think the axis just determines the sign

leaden ice
# heady iris i think the axis just determines the sign

I have no idea why they changed it but the old documentation has a very nice analogy in it:
https://docs.unity3d.com/2020.2/Documentation/ScriptReference/Vector3.SignedAngle.html

If you imagine the from and to vectors as lines on a piece of paper, both originating from the same point, then the axis vector would point up out of the paper. The measured angle between the two vectors would be positive in a clockwise direction and negative in an anti-clockwise direction.

heady iris
#

The motivation here is to get a spectator camera (which uses yaw and pitch) aligned with whatever viewpoint you had before resuming spectator mode

green oyster
#

I got this spline, it starts of with 2 points, i get the last points REAL WORLD pos, and i add a new point to this spline, to the same world pos as the last one, so in theory the new points should always be at same place as the second point, but this does not happen, instead they somehow are getting further apart and it makes no sense?

#
          for (int i = 0; i < sceneCreation.drawSetting.amountOfPoints; i++){
               Vector3 newPointWorldPos = shapeController.transform.TransformPoint(spline.GetPosition(spline.GetPointCount() - 1));
               //newPointWorldPos += new Vector3(lengthBetweenPoints, 0f, 0f);
               print(newPointWorldPos);
               spline.InsertPointAt(spline.GetPointCount(), newPointWorldPos);
#

im not adding anything to the new points position

#

so i dont understand why the new points would be in different places

heady iris
#

...i was using the brain's transform

leaden ice
heady iris
#

(the brain is not the thing that rotates!)

green oyster
leaden ice
#

yes

green oyster
#

but after i did the TransformPoint of it

#

it should be in world place converted

leaden ice
#

so wouldn't it follow that insertion also uses local space?

#

WHy would you get in local but insert a world space point?

#
Vector3 lastPoint = spline.GetPosition(spline.GetPointCount() - 1);
spline.InsertPointAt(spline.GetPointCount(), lastPoint);``` It should be this simple, no?
heady iris
green oyster
#

they converted mouse point to world pos, and then passed it into the insertion

leaden ice
#

in that example they're just using an object at the origin with uniform scaling so world space and local space are the same

#

they're sidestepping the issue

#

you can't sidestep the issue

heady iris
#

i've done exactly this before :p

#

i am now pointing in various directions. i love vectors.

green oyster
heady iris
#

yes, because you need local space, not world space

#

it won't worked in that code above because world-space and local-space are equivalent if you have no parent and your transform is the default

#

0 position, no rotation, 1 scale

green oyster
#

So the mouse screen position to world point was the same as the spline local space?

heady iris
#

Yes, because the two spaces were equivalent

#

transform.InverseTransformPoint goes from world-space to local-space

#

it would be used if the spline weren't guaranteed to have a default transform

shell scarab
#

I haven't worked on a 2D project in quite some time, but I seem to remember this working? I feel like that's how I've always done it.

private void FixedUpdate()
{
  Vector2 vel = rb2d.velocity;
  /*rb2d.velocity =*/ Vector2.SmoothDamp(rb2d.velocity, moveVector * movementSpeed, ref vel, movementDelay, maxSpeed, Time.fixedDeltaTime);
  rb2d.velocity = vel;
}
heady iris
#

sure, that'll smooth-damp your velocity towards the desired velocity vector

shell scarab
#

but it doesn't D:

#

these values:

heady iris
#

oh wait, you do nothing with the result

shell scarab
heady iris
#

oh I see what you did

shell scarab
heady iris
#

SmoothDamp takes several parameters:

  • the value to go from
  • the value to go to
  • a ref parameter for the velocity (how quickly the value changes)
  • the time taken to move
#

The third parameter is how quickly the value is changing

#

It's not the value

shell scarab
#

not the 4th value?

heady iris
#

Forget entirely about how you're trying to mess with a rigidbody's velocity

#

the terms are overlapping here

#

currentVelocity is how quickly the smooth damp is changing your value right now

#

It's passed by ref so that it can be updated by the SmoothDamp method

#

the method returns the updated value

shell scarab
#

ohhh. Ok, in that case it should be a field value. Documentation is really not clear on that.

heady iris
#

You're getting confused because your value is, itself, a velocity

heady iris
shell scarab
#

yea I get it now

#

i feel like if the docs said "The current velocity of the function, this value is modified by the function every time you call it." or something instead of "The current velocity, this value is modified by the function every time you call it." it would be more clear.

#

or at least add in the description "currentVelocity should be a field value" or something. There's no example on how to use D:

heady iris
shell scarab
#

in Vector3.SmoothDamp D: of course they would

#

I was looking at Vector2.SmoothDamp

heady iris
#

ah

#

oh yeah that is just missing

shell scarab
#

smh

heady iris
#

i submitted feedback

robust dome
#

any freaking channel where one can ask blender related things?

somber nacelle
#

there's a whole !blender discord

tawny elkBOT
robust dome
#

yep i know, anyways ty

somber nacelle
#

great! then you know where your blender related questions belong

shell scarab
# shell scarab not the 4th value?

also@heady iris another thing,

Approximately the time it will take to reach the target. A smaller value will reach the target faster.
but when 0 doesn't move? 🤔 for 4th parameter

heady iris
#

i wouldn't be surprised if it broke

#

although, it looks like smoothTime is clamped from below to like 0.0001f

#

perhaps you mean the 5th value?

#

that's the maximum speed to move at

shell scarab
heady iris
#

show your code.

shell scarab
#

seems to only happen when Time.fixedDeltaTime is supplied to it

#
   private void FixedUpdate()
    {
        rb2d.velocity = Vector2.SmoothDamp(rb2d.velocity, moveVector * movementSpeed, ref moveSmoothVel, movementDelay, maxSpeed, Time.fixedDeltaTime);
    }
#

well when i tested it maxSpeed was at 100

heady iris
#

ah

#

it calculates maxSpeed * smoothTime at one point

#

i dunno what the rest is doing; i'm just looking at what VSCode can give me

#

this happens after clamping smoothTime to 0.0001f, but it still might be so small you get weird results

shell scarab
#

actually it works but it's so bizzar man. if I set max speed to 1 thousand it works

heady iris
#

yeah, because of that clamping

shell scarab
#

sorry, 10 thousand

heady iris
#

you can really just make maxSpeed be infinity

#

that's the default

#

float.Infinity

#

er

#

Mathf.Infinity

shell scarab
#

Mathf.Infinity

#

yea i am

#

just weird

heady iris
shell scarab
#

I was assuming maxSpeed was how fast the ref velocity parameter would be allowed to change

#

like measuring its magnitude or something

heady iris
#

That is correct.

#

at least, it's the effect it has

#

I dunno how it interacts with the rest of the calculations exactly

shell scarab
#

so feel like it should still move even when max speed is 100 and smoothTime is 0

heady iris
#

oh wait, not how fast it could change

#

it's just how big it can be

shell scarab
#

yea

#

oh well, just a weird quirck ig

tall pewter
foggy pasture
#

yo, could anyone explain how this is possible

leaden ice
foggy pasture
#

that was indeed the case

#

i'm a little stupid

#

man you are crazy

#

you helped me like six months ago too

shell scarab
#

don't need help, just sharing the sadness

heady iris
#

ref fields are a pretty weird thing to use

cold parrot
heady iris
#

ref fields are solely used in ref structs

#

are you thinking of something else?

cold parrot
swift falcon
#

ok, so im kinda stuck with something i cant seem to find an answer to with google, soooo, is it possible to create a undetermined amount of tmp text sprites at runtime? or some other neat way of adding them to tmp text? as im currently using 4 raw images outside of the text which are fun and all, but if the book im loading contains more then 4 images in that chapter, i cant display those.

rigid island
#

Uhh anyone know why the ContextMenuItem doesn't work ? I literally copied it from the docs and its not appearing.. The ContextMenu does work though.

 [ContextMenuItem("ResetName", nameof(ResetPlayerName))]
    public string playername = "";

    void ResetPlayerName()
    {
        playername = "";
    }

    [ContextMenu("SumMethod")]
    void SumMethod() { }```
leaden ice
rigid island
#

Ohhh oops.. duhh need to right click the Field that has the ContextMenuItem... Makes sense 😛

leaden ice
#

Ah yeah I assumed you'd done that in the screenshot 👍

rigid island
mystic ferry
#

I had a problem I was stuck on for hours, I had 3 different attempted solutions and when I went to think of how to word the question I was gonna post here, I revisited one of my attempted solutions to find it worked perfectly

#

game dev is hard.

#

it's crazy how you can try to solve something, have absolutely no idea how it didn't work, and then when you try the solution again it magically works and you have no idea why it didn't work before

fallen garnet
spring creek
#

And referencing something that isn't static (positions change)

#

So it needs to be inside a method

#

You may want to do:

private Vector2 temp;

At the top, outside any method.

Then at the start of MoveBox, probably just after the if check, do:

temp = transform.position;
#

And I would rename that variable to like... currentPosition or something

spring creek
#

You are changing Speed_Move is set after using it to add to temp.x, for one thing.

#

Also, both the if and else if multiply by -1. Is that intended?

#

What is speed_move set to? 0 times 1 or -1 is still 0

fallen garnet
tame urchin
#

Is there a callback I can call for when a ScriptableObject .asset file is first created? Like MonoBehavior.Reset() ?

tame urchin
#

Hmm yeah. It looks like ScriptableObject.Reset() works fine

ruby nacelle
#

Hey, I'm trying to add Acceleration and Deceleration to smooth the movement of my character, but the values are stuck on applying force to only the right side of the characters, maybe I missed something small but I can't seem to find the issue

    // Update is called once per frame
    void FixedUpdate()
    {
        if (!isAlive) { return; } // If the player is not alive, do nothing

        ClimbLadder();             // Handle climbing on ladders
        Die();                     // Handle player death

        if (!_isRolling)
        {
            run();                 // Handle player's running
            FlipSprite();          // Flip the player sprite based on movement direction
        }
    }

    // Input handler for player movement
    void OnMove(InputValue value)
    {
        moveInput = value.Get<Vector2>(); // Get the movement input
    }

    // Function to handle player movement
    void run()
    {
        float targetSpeed = moveInput.x * _runSpeed; // Set the target speed to the constant run speed

        float speedDiff = targetSpeed - rb2d.velocity.x;

        float accelRate = (MathF.Abs(targetSpeed) > 0.01f) ? acceleration : decceleration;

        float movement = MathF.Pow(MathF.Abs(speedDiff) * accelRate, velPower * MathF.Sign(speedDiff));

        rb2d.AddForce(movement * Vector2.right);

        // Check if the player is running and update the animator accordingly
        bool playerHasHorizontalSpeed = Mathf.Abs(rb2d.velocity.x) > Mathf.Epsilon;
        animator.SetBool("isRunning", playerHasHorizontalSpeed);
    }```
#
    public float decceleration = 7f;
    public float acceleration = 7f;
    public float velPower = 0.9f;
    [SerializeField] float _runSpeed = 5;             // Running speed```
swift falcon
#

public float decceleration = 7f;
public float acceleration = 7f;

#

isn't one supposed to be negative?

#

or something

#

not sure I understand what you are doing

ruby nacelle
# swift falcon Listen up brother. your decceleration and acceleration values are the same. Wha...

It's just for testing, I haven't been able to get a chance to test both values properly I've commented what the code is intended to do to make it easier to read


    // Input handler for player movement
    void OnMove(InputValue value)
    {
        moveInput = value.Get<Vector2>(); // Get the movement input
    }

    // Function to handle player movement
    void run()
    {
        //calculate direction and desired velocity
        float targetSpeed = moveInput.x * _runSpeed; // Set the target speed to the constant run speed
        //calculate difference between current and desired velocity
        float speedDiff = targetSpeed - rb2d.velocity.x;
        //change accelration rate depending on situation
        float accelRate = (MathF.Abs(targetSpeed) > 0.01f) ? acceleration : decceleration;
        //apply acceleration to difference, then raise to a set power so acceleration increase with higher speeds
        //multiples by sign to reapply direction
        float movement = MathF.Pow(MathF.Abs(speedDiff) * accelRate, velPower * MathF.Sign(speedDiff));
        //apply force to ridgidbody, multiplying vector2.right so only affects x axis
        rb2d.AddForce(movement * Vector2.right);```
swift falcon
#

I think it's because you are using Mathf.Abs, so the values are always possitive, meaning the character will always move right

mystic ferry
#
_rb.transform.position = Vector2.MoveTowards(_rb.position, _player.transform.position, _monsterSpeed * Time.deltaTime);

works fine, but replacing _rb.transform.position with rb.velocity causes some strange issues. Can anyone explain this disparity?

leaden ice
#

they are not interchangeable

mystic ferry
#

I'm a bit confused, MoveTowards returns a vector, so what makes that only applicable to position? not sure what I'm missing

leaden ice
#

positions

#

velocities

#

euler angles
colors

#

you cannot simply use any vector anywhere

#

just like how a number can mean a weight, or an age, or an amount of time

#

they are not interchangeable just because they are numbers

mystic ferry
#

I understand the sentiment but I don't understand how that's the case here

leaden ice
#

_player.transform.position is a position vector
_rb.velocity is a velocity vector

#

you cannot intermix them directly

#

that's all

#

it's that simple

#

you cannot simply say _rb.velocity = _player.transform.position; and expect something sensical to happen

cosmic rain
leaden ice
#

the result of Vector2.MoveTowards when you pass in two position vectors is also a position vector. It cannot be used as a velocity.

#

Of course, it's not clear exactly what code you wrote when you tried what you tried, since you didn't share it, but I'm making an educated guess here.

mystic ferry
#

that puts quite a few pieces together that I was apparently missing. I never really thought they were completely separate vectors and just thought of modifying the transform directly as "teleporting" the object rather than updating the position vector

#

thank you for the help :)

worn stirrup
#

Hey all, trying to figure out how to write this together because I'm pretty sure it can? CS f (!Mathf.Approximately(vacuumHeight, targetHeight)) { //POINT UP if (vacuumHeight > targetHeight) { vacuum.AddForce(new(0, -vacuumTurnStrength * (1.5f - Mathf.InverseLerp(startHeight + 0.9f, targetHeight, vacuumHeight)))); } //POINT DOWN else if (vacuumHeight < targetHeight) { vacuum.AddForce(new(0, vacuumTurnStrength * (1.5f - Mathf.InverseLerp(startHeight - 0.9f, targetHeight, vacuumHeight)))); } }

#

The code is basically the same both ways, it's just comparing two floats and inverting a couple values internally based on the difference in the floats, how do I shrink this down?

leaden ice
worn stirrup
#

that seems correct, would just need to apply the -1 to the 0.9f

leaden ice
#

ah missed that bit

worn stirrup
#

thank you, I'm gonna try it

worn stirrup
#

Oh I forgot to say anything, that works perfectly, thanks!

vague tundra
#

Does anyone know of a more light-weight alternative to the LineRenderer component?
I want to draw 2D lines, no lighting or anything like that.

gray mural
#

Is ScriptableObject reference or value type?

#

I guess reference

fervent furnace
#

it is class

#

so reference

#

and you cannot inherit from value type (all the structs) or vice verse iirc

latent oak
#

hallo peeps, I was wondering. I have an inventory system. however I wanted a cursor to appear like a selector on the top corner of the slot when the user is using a gamepad(pretty typical i feel). Is this relatively easy utilizing the new input system, and how can I calculate the navigation without making thee slots buttons or maybe I need them to be buttons, but any advice would be great

blazing smelt
#

So I think I asked the other day but didn't get a response - Unity's IAP system seems to be designed around loading products in big batches, instead of one at a time. Is there a particular reason for this? I'm refactoring some existing code somebody else made, that seems to be designed around adding products one at a time at a certain point, and I'm wondering if I need to change it so they're added before in a batch.

Does this question make sense? The code is overly complicated so I tried to only mention the relevant stuff so as to not waste time.

mossy snow
#

What does "big batches" mean? Why would you load them one at a time? You aren't likely to have more than a few dozen at most

digital umbra
#

Why can't I send my code?

mossy snow
gray mural
#

is it possible to make all children images to change their alpha when parent's alpha is change?

#

without writing my own script

mossy snow
#

group them under a canvas and attach CanvasGroup. Use the CanvasGroup alpha

wanton wasp
#

I don't know, if it is the right place to ask. Anyways, I've got an error, when creating a 2D project from the template. The error itself coming from TestRunner module.
Library\PackageCache\com.unity.test-framework@1.1.33\UnityEditor.TestRunner\CommandLineTest\TestStarter.cs(1,1): error CS1056: Unexpected character '
Things I've already tried:
Restart Unity
Reboot
Reinstall Unity completely
Deleting library folder

Version: 2022.3.8f1, 2022.3.51f

I can't just delete Test Runner package, because 2D package depends on it.

prime sinew
#

Are you able to view the TestStart.cs file?

wanton wasp
simple egret
#

👀

#

Filled with null characters

prime sinew
#

not at all what I was expecting.. that is really weird

#

i've got no idea

wanton wasp
#

Can someone tell me the version of the test runner in your project?
Maybe the 1.1.33 version is broken.
Upd: it's actually called Test Framework

lucid wigeon
#

Any log manager which would allow me to switch logs off per component or per gameobject or per class to reduce spam? Obviously I can comment out logs but that's not the point.

blazing smelt
wanton wasp
mystic ferry
#

I'm writing some simple AI, think like the skeleton from minecraft where it chases the player if they're too far away, and once they reach a certain threshold they start a ranged attack. How would I specify whether the player is in "chase" range, vs "attack" range? it seems intuitive to have a child gameobject with a second istrigger collider, but I think that'll require a second script to talk to the parent which seems unelegant. What do you guys do?

#

I just realized a state machine that checks distance each frame in the move state sounds like it’ll work fine but still curious what y’all do

tardy basin
#

Hi, can anyone advice me on how can I take input from the user in the Dedicated Server console?

wanton wasp
wanton wasp
mystic ferry
heady iris
#

I will use (trigger) colliders to detect things in the first place.

#

That is one area I need to profile. I'm not sure which of these is smarter:

  • Just test distance against everyone
  • Use a physics query to find nearby entities, then test distance against just those
#

Physics queries should scale better. Probably 😉

wanton wasp
# heady iris That is one area I need to profile. I'm not sure which of these is smarter: - J...

It depends on your needs.
If you have a small group of enemies, which should change state depending on the distance to the player, both will do.
But, if we are talking about 100s of enemies it can create a heavy load on the cpu, depending on the distance check formula. For example, Vector3.Distance is slower than (playerPosition - transform.position).sqrMagnetude, I could be wrong, maybe unity have optimized the distance method

Generally speaking, physics things are almost always slower than plain math.
I can't advice the best solution to you, because I don't know what type of game you are making.

untold nebula
#

GUYS I am making a multiplayer game using photon and i need help

wanton wasp
untold nebula
#

its a top down game shooter i just want to make a gui for them

rigid island
#

stay in 1 channel

untold nebula
#

ok

rigid island
atomic fractal
#

I will post my question here, it might be suited better here

hey everyone, im having a problem.
I try to make a spell effect to be exactly as far as my hitbox. Lets say my Firelance should be 6 units long. But when my balancing decides to go for 7 units, i would have to redesign the effect, and that does sound annoying... is there a good way to have a Particle Effect / System or something that rescales to a single factor ?
i hope my question makes sense

rigid island
atomic fractal
rigid island
#

Im not even sure what ur asking here

heady iris
#

sounds like you need to set parameters on your particle system through code, yes

#

this is more straightforward in the Visual Effect system. you'd just add a Property for the length, and use that to decide how to position the individual particles

atomic fractal
heady iris
#

speed is distance / time

atomic fractal
heady iris
#

you know distance and want time

#

divide the distance you want by the speed

#

10 meters at 5 meters per second = 2 seconds

atomic fractal
heady iris
#

A rather old version, but yes

#

should still do what you need, if you want to try using it

severe sable
#

Enums are fairly useless since they don't store any data themselves and need a function to read them. Having a state as an enum is only as useful as the function checking what state there is, and this could be better done through a class as then the data and functions can be stored within it instead of creating more bloat code for reading enums correct?

heady iris
#

But if you're already using particle systems everywhere, I would not switch just for this

heady iris
atomic fractal
heady iris
#

switch statements give you very similar behavior to polymorphism: you pick the code to run based on the value of the enum (vs. the type of the object)

severe sable
#

Currently working on a game and I've found myself using enums a few times and have noticed that each time, can you think of some good examples I can utilize them?

heady iris
#

well, I just wrote a little debug utility that lets me place entities and give them commands

#

it just has a few modes

#

...I haven't actually put any code in there yet!

#

but that's how I'm going to perform actions when entering and exiting modes

fervent furnace
#

i sometime use enum in ondrawgizmos to draw different things for debug

heady iris
#

I could create an entire state machine for this

#

but I really don't feel like adding a bunch of classes that individually do very little

severe sable
#

hmm, not going to lie I was hoping for someone to tell me I'm completely wrong and I was using enums incorrectly and they had much more power than I thought

heady iris
#

they don't have magic powers

severe sable
#

They don't have any powers haha

heady iris
#

it's just that, for small problems, you don't need a seven layer bean dip of polymorphic abstraction

heady iris
#

you need a dang switch statement

#

I use state machines for my entities

severe sable
#

Makes sense

heady iris
#

Different entities can have wildly different sets of states

severe sable
#

See I've got a really weird issue that I feel like has to be super common

heady iris
#

If the set of states is constant, and each state is pretty small, I just write if/else chains or switches

severe sable
#

You know games that involve a player dragging and dropping parts onto other ones that connect?

ashen yoke
#
static MyEnum
{
    public const int Value1 = 0;
    public const int Value2 = 1;
    public const int Value3 = 2;
}

int val = MyEnum.Value2;

this serves the same purpose

heady iris
#

public const int TheNumber3 = 4;

the inevitable catastrophe 😉

severe sable
#

I am currently trying to figure out how on earth to store this data and use it. (regarding an Attach point system) I did some brainstorming and I was really hoping for some input on how to approach this issue. could you guys help perhaps?

ashen yoke
#
enum MyEnum
{
  TheNumber3 = 4
}
fervent furnace
#

i often use static class consists of const int since i need my enum to be array index
but extremely dangerous

ashen yoke
#

i dont understand

heady iris
#

oh, that was a bit of a tangent. it wasn't actually really relevant here...

#

i was thinking of when you have constants whose name is literally just the content of the constant

#

(you see it in CSS sometimes)

but yes, that is actually completely irrelevant. oops.

ashen yoke
#

easy to spot an error

#

if its a convention

fervent furnace
#

or change enum to byte which consume fewer memory

severe sable
#

Do you guys have any idea? I've asked around a few times and even been pestering chatGBT for ages trying to get a prompt to give me some good examples of how to approach this with little luck 😦

heady iris
severe sable
#

Should I store those as vectors or should I just have an attached gameobject that is a attachpoint?

heady iris
#

Transforms are nice because you can parent another object directly to them

#

you also get to see and move them in the editor for free

severe sable
#

so a child gameobject right? since I have prefabs for blocks already

ashen yoke
#

you can write a semi automatic authoring tool that setups initials

#

then you manually adjust after initial point gen

heady iris
ashen yoke
#

but it still needs to be human validated

#

you can write validation code that notifies you of errors

severe sable
#

That would be amazing and just what I was looking for, but I will be honest, I have not done that before, and only recently learned how to make my own enums show in the inspector through serialize field

ashen yoke
#

and so on, you help yourself with things that can speed up content production, but you cant completely automate everything unless you have a very strict set of constraints

severe sable
#

Where can I start learning?

ashen yoke
#

just do stuff, start with something

severe sable
#

How would I go about auto generating that, and aren't I unable to do that in the edit mode?

#

I was thinking about that a lot

heady iris
#

welcome to the world of editor scripting (:

#

Play Mode and Edit Mode aren't that different

severe sable
#

Since you need to run the game for the code to execute so how do you get it to run and still be in edit

severe sable
ashen yoke
heady iris
#

Play Mode just keeps you safe

ashen yoke
#

even run physics

heady iris
#

The game is always running.

ashen yoke
#

and animations

lean sail
#

There are a few easy options too like context menu or menu item which you can run code at the click of a button.

heady iris
#

there is no spoon

severe sable
#

and quick question, when I build this, that code will be taken out or seperated right?

ocean river
#

ah guys i have a question.
is it possible to create a curve between 2 objects?
i want an specific object to move along that curve for a second, but also, if possible, bent the character fitting to the curve.

ashen yoke
#

editor code stays in editor

severe sable
#

like if I adjust where an instance of a gameobject that an editor script generates in the editor, it won't be localized and reset on a build that gets published?

ashen yoke
#

not sure what you mean by that

severe sable
#

I'm finding it a bit hard to explain, let me give it another go

lean sail
severe sable
# ashen yoke not sure what you mean by that

So lets say we make this script that will automatically place some attachpoints where it thinks they go, and then once it does that I decide that one of them is good, but lets say another isn't good and I remove or move it slightly, will I be able to keep these changes when I go into play mode? since usually play mode executes a bunch of scripts over again, it wouldn't reset the position of the object I decided I wanted to manipulate?

ashen yoke
#

same way you manipulate prefabs in editor

#

data is serialized into the object you are editing

#

which is then used in playmode

ocean river
severe sable
#

I think I understand, but this a bit confusing and also really interesting and I tend to find I learn best by doing, do you know if there's a example github of a concept like what you are talking about?

heady iris
#

the editor scripts would modify your game data.

lean sail
heady iris
#

their job is now done

severe sable
lean sail
#

Editor script place objects around*

severe sable
#

but how do I even create a script for this, it's obviously not derived from monobehavoir

ashen yoke
#

create a test script,
create a custom inspector for it,
add Vector3[] array to it,
in the custom inspector in OnSceneGUI, use Handles class to draw spheres that are associated with points in that array,
use Handles transform gizmo to move points around,
result is you can click, drag, delete points in that array

#

after that everything else will be clear

severe sable
#

Ok, I will try that now, ill ask if I have questions

ashen yoke
#

i outlined a learning path, which involves lots of reading at each step

lean sail
ashen yoke
#

result will be you ready to tackle the custom editor for your purposes, somewhat

round creek
#

hey, does anyone know how i can get sharper/crisper shadows? right now they look pixelated to a degree. (3d urp, directional light)

severe sable
ashen yoke
#

yes

#

i also recommend new project

severe sable
#

is there a risk if I dont use a new project haha

ashen yoke
#

it just will be slower

#

empty project - instant compilation, fast iterations

severe sable
#

ah fair then it should be fine, mine doesnt take too long

severe sable
vivid remnant
#

How can I get the velocity of a rigidbody right before a collision?

rigid island
#

stop storing when collided

vivid remnant
#

Should I use FixedUpdate() in order to store the velocity?

#

Is OnCollisionEnter() always called after FixedUpdate()?

vivid remnant
#

So it is better to store the velocity of an object relative to the object it collides with. Found some forums where people were saying the same thing. Noted with thanks!

heady iris
#

FixedUpdate executes immediately before the physics simulation updates, btw

mystic ferry
#

I know this is bad code but it's just some prelimary tests but I'm absolutely baffled by the logs. For some reason the logs show _timeToRemainStillAfterMoving as negative, and it's causing a lot of strange behavior. I have no idea how it's even possible to get a negative value here

#

I'm setting the variable equal to a random range between 2 and 3, and it somehow spits out negative

fervent furnace
#

you setting it after waiting

heady iris
#

RandomMove waits for 3 to 6 seconds before reassigning _timeToRemainStillAfterMoving

#

It's also getting started every single frame

ashen yoke
#

yes

#

guard it somehow, a bool or state check, ideally

mystic ferry
#

man that's tricky. Surprised that was so obvious for you guys to spot lol

ashen yoke
#

you should abstract your states

mystic ferry
#

I will, like I said I knew it was bad code, I was just confused by the logs

heady iris
#

Pay attention to how you "guard" each part of your code.

#

the path taken to reach it

#

your condition for wandering should be "I am not wandering yet AND I'm done standing still"

earnest gyro
#

what's the best way to avoid NullReferenceExceptions? Currently, I'm putting in if (_myObject != null) everywhere but that can't be correct. I think it's related to the call order: create a monobehavior > update gets called > set an attribute with a public method. And so I wind up with nulls because I think update (needing a specific attribute that hasn't been set yet) gets called maybe a frame or 2 before actually setting the attribute?

ashen yoke
#

what is "set an attribute with a public method"

fervent furnace
#

ofc you have to figure out the dependencies

mystic ferry
heady iris
earnest gyro
#

well it's a monobehavior, so I can't pass variables into a constructor, but I do want to set certain attributes from outsidethe monobehavior. So for example, I have like SetColony to set the _colony attribute of this monobehavior

heady iris
#

Awake runs on every object in the scene. Start then runs before the first Update.

#

Awake also runs instantly on every enabled monobehaviour when you instantiate an active gameobject

earnest gyro
heady iris
#

If you need to do something before the next frame, but also need to configure something first, you'll need to have an Init method that you call manually or something similar

heady iris
earnest gyro
earnest gyro
heady iris
#

e.g.

#
var thingy = Instantiate(myPrefab);
thingy.gun = someGun;
thingy.faction = Faction.Dudes;
thingy.Init();
#

Init could then do something with the gun and the faction

#

Awake runs as part of instantiation, and Start runs in the next frame

earnest gyro
#

I see

heady iris
#

I recently had a problem where my spatial audio sources could get asked to play a sound before their Start method had a chance to run

#

so I threw in a manual Init method

earnest gyro
#

But like I've got code like that in the Start of another object

glass verge
#

colliders

shell scarab
#

@heady iris you familiar with Dictionary and SortedDictionary?

heady iris
#

ask your question

shell scarab
#

I was wondering if I should switch to using a SortedDictionary instead of a Dictionary if I don't expect to have a lot of elements in my collection.

heady iris
#

use SortedDictionary if you need to access the dictionary's contents in key-sorted order

shell scarab
#

yea but I believe for smaller number of items SortedDictionary is faster

heady iris
#

well, if you believe it, then go ahead and do it

#

i don't know the gory details of the implementations

#

SortedDictionary is a tree and Dictionary is a hashtable

#

log(n) comparisons vs. a constant-time hashing and lookup

shell scarab
#

yea ik, which means it's O(log(n))

heady iris
#

i suppose it could be slightly faster if hashing is expensive

#

profile it if you think there's some kind of difference to be had

earnest gyro
#

Help with a NullReferenceException

shell scarab
#

O(log(n)) could be faster for a while than O(1) depending on how fast O(1) is. I can't find any details on how fast A dictionary actually is.

fervent furnace
#

search in binary tree is O(log(n)*size of key) while hashing is O(size of key)

#

hashing is not O(1) actually unless you pre compute the the code

heady iris
heady iris
shell scarab
heady iris
#

accessing it requires hashing the key, yes

shell scarab
#

oops yea, interesting, everything I read online says it's O(1)

fervent furnace
#

btw in many case i believe the code will be pre computed

heady iris
#

It is constant-time for a fixed-size key

ashen yoke
#

the O means different things in different contexts

fervent furnace
#

and stored

ashen yoke
#

you can find massive examples of claimed O(1) when its actually deeply not 1

#

its just 1 relative to other algorithms

heady iris
#

well, O(10000000) is still O(1)

ashen yoke
#

and discards details

heady iris
#

but you can certainly get bitten by the constant

shell scarab
#

my key is a Vector2. It's hash function shouldn't take longer sometimes and less time other times, right? So it should be O(1) if it's precompiled.

heady iris
#

yes, that's going to be constant-time

#

all of this is bikeshedding. just use the dang dictionary and go make your game :p

#

i need to run for a bit

shell scarab
#

That actually explains why it takes around 8 milliseconds for my pathfinding to work the first time then like 3 other times, bc of the JITC

ashen yoke
#

unitys vector hashing is also slow

shell scarab
ashen yoke
#

probably they chose the safest less collision spookyhash

shell scarab
#

or int2's hashing

ashen yoke
#

i checked the method with deep profiler

ashen yoke
#

vectors use spookyhash

twilit egret
#

Hi, I'm not sure if this is the right place to ask this question, but I'll give it a try.

I am currently working my way through the Open Game Project "Chop Chop" (https://github.com/UnityTechnologies/open-project-1) to learn more about Unity.

In the Initializer Scene, the LoadEventChannelSO is loaded as AssetReference Async. However, in the following scene, the PersistenceManagers scene, the LoadEventChannelSO object is referenced directly in the SceneLoader (not via AdressableScript, which would have to be loaded first).

I don't understand why. Can anyone tell me why this was done?

GitHub

Unity Open Project #1: Chop Chop. Contribute to UnityTechnologies/open-project-1 development by creating an account on GitHub.

latent wadi
#

How can i make something follow the mouse if the mouse clicks within certain bounds, for example i want to have a system where you can view a 3d model of a gun and use the mouse to interact with it like pulling back the bolt or removing the magazine by clicking and dragging. Is there a way to do something like hitboxes or something around the separate intractable parts and say that if the mouse is over those "hitboxes" that part is interacted with?

heady iris
#

You need to translate the mouse position into an appropriate world position

#

to start the interaction, you'd just raycast and see if you hit a collider on an interactable thing

latent wadi
#

currently i have something like this, when you press mouse 2 you can drag the mouse to rotate the model

heady iris
#

for something like a bolt, you could use Plane to define a plane along which the bolt moves

#

and then use its Raycast method to figure out where on that 2D plane the mouse is pointing

#

then you'd need to decide where to put the bolt based on that

latent wadi
heady iris
#

sounds like something that Vector3.Project and Vector3.ProjectOnPlane could do. I'd need to think about that a bit.

heady iris
#

Imagine turning a mouse position into a value between 0 and 1

#

0 is the bolt all the way back; 1 is the bolt all the way forward

#

you're find the closest point on a line to the mouse

#

and then figuring out how far you are along that line

heady iris
#

I know I've done that math before

#

I guess you'll want to figure out what "kinds" of controls you'll need

#

certainly a 1D axis

#

and one for rotation around an axis

#

e.g. to unfold a stock

#

for moving a magazine around, you could do 2D movement: lock it into the plane of the firearm and move it around on there

#

and maybe a kind that doesn't move at all

#

like clicking to change the position of a safety

latent wadi
#

Hmmm, alright, i'll probably just try out some of the stuff you mentioned and mess around with scripts for a while and see what works for me

tawny elm
#

i currently have one script thats inheriting from another.
im trying to have the inhereted script execute a void inside the ones inheriting from it but it wont work.

tawny elm
knotty sun
#

Oh, you mean a method?

tawny elm
#

well it says void there so i didnt think there would be any communication error

knotty sun
#

void is a return type not a description of what it is

tawny elm
#

i know thats not technically what it is but i really dont think anybody else would be confused on what i was trying to talk about

knotty sun
#

not confused, just trying to educate you in correct termimology

#
void Awake()

is the signature of the Awake method

tawny elm
knotty sun
#

correct

shell scarab
#

its ok, it was a communication error. You would say "a function" or "a method" not "a void", "a void" doesn't really make sense

tawny elm
shell scarab
#

no they just said they're not confused

knotty sun
#

this server is as much about education as helping, when you ask questions to get good answers using the correct terminology will help your cause

#

but to answer your original question
you are using the wrong access modifier which is why the inheriting class cannot see the inherited method
See what I mean about terminology?

vague sedge
#

trying to figure out walking along walls, ive almost figured it out but not competely, it rotates around the worlds z axis but not around the x axis, and im unsure how to fix this

#

rough outline of how it rotates around the object

olive sedge
#

I have never used text mesh pro before and I am a huge dumb

dense vessel
olive sedge
#

I'm trying to change the text of a TMP component on awake but it's complaining the component is missing

#

What on Earth is going on?

#
using TMPro;
using UnityEngine;

public class ChangeTextOnStart : MonoBehaviour
{
    TextMeshPro _textMeshPro;

    void Awake()
    {
        _textMeshPro = GetComponent<TextMeshPro>();
        _textMeshPro.text = "Hello, World!";
    }
}
dense vessel
#

Be careful that there are I think 3 classes with similar names, pick the right one 😉

somber nacelle
#

keep in mind that TextMeshPro is the non UI version. you can use TMP_Text for the type for either the UI version (which is actually TextMeshProUGUI) or for the 3d text version which is the one you are using

olive sedge
#

This is why I was extremely confused

somber nacelle
#

yeah that's not a TextMeshPro component

#

that's a TextMeshProUGUI component

olive sedge
#

Why are they different things that's a beginner's trap

somber nacelle
#

use TMP_Text if you don't care which of the two types of text mesh pro text components you are using.

olive sedge
#

It's working now

#

That's the important thing

heady iris
olive sedge
#

OK so now that I've got that figured out, I can't get TMP to play nice with my assembly definition.

#

I've included them as references into the necessary script and yet it's still complaining that I don't have the right permissions to include it as a library.

somber nacelle
#

remove the reference to the editor assembly there unless you want issues when you go to build. and you need to be more specific about what your actual issue is

shell scarab
#

does deep profiling affect performance if you didn't turn it off after you close the profiler?

olive sedge
somber nacelle
#

why not share what the error says? that would be how you can be more specific

olive sedge
#

So this script obviously doesn't work, but I'm really interested in that second line.

somber nacelle
#

and does the error appear only in your IDE or do you see it in the unity console as well

#

also _textMesh = GetComponent<TextMesh>(); is wrong

olive sedge
#

Severity Code Description Project File Line Suppression State
Error CS0246 The type or namespace name 'TextMeshPro' could not be found (are you missing a using directive or an assembly reference?) LunaRoseManor.Spacewar.Events C:\Users\******\Working\unity-spacewar\Assets_Project\Scripts\Events\IncrementTextOnDestroy.cs 2 Active

#

I'm only interested in why the library isn't being included

#

I know how to fix everything else

somber nacelle
#

again, does the error appear only in your ide or does it appear in the unity console as well

#

i'm not asking questions just for shits and giggles mate

olive sedge
#

I'm a big dumb

#

The editor shows on both the IDE and Unity

#

But The library isn't called "TextMeshPro", it's "TMPro"

#

It's a very similar issue to before where we have different names for things.

somber nacelle
#

also for future reference, it's a namespace not a library

heady iris
#

indeed: I don't think that "library" has a technical meaning in C#

stark sun
west sparrow
# olive sedge It's a very similar issue to before where we have different names for things.

I know it doesn't matter much, but it's partially because TMP was made by some guy in a basement, and was eventually bought and added into Unity directly, and had little more than life support since. It has always been a bit of an ugly workaround for textboxes imho, but was a lot better than the standard text boxes (which Unity created about 9 years back).

There is a lot it doesn't do or does poorly that makes it awkward to work with the first time. Even RTL text, non-english character sets, etc. All unnaturally difficult to work with.

#

That said it's still better than the existing, and was bought and brought in. So it's kind of a messy standard - IMHO

west sparrow
#

When you say not stopping, as in not at all, or just slowly

stark sun
#

At normal they follow me in a range

west sparrow
#

Assuming you aren't running OnTriggerEnter over and over and having a whole bunch of coroutine instances running

stark sun
mossy snow
stark sun
west sparrow
stark sun
#

I will try thanks

west sparrow
#

From there, you'll need to debug and look at if NotMoving is ever executed

severe sable
# ashen yoke https://docs.unity3d.com/Manual/UIE-HowTo-CreateCustomInspector.html
using Content;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine.UIElements;

namespace Editor
{
    [CustomEditor(typeof(Block))]
    public class BlockInspector : UnityEditor.Editor
    {
        public override VisualElement CreateInspectorGUI()
        {
            // Create a new VisualElement to be the root of our inspector UI
            VisualElement myInspector = new VisualElement();

            // Add a simple label
            myInspector.Add(new Label("This is a custom inspector"));

            // Return the finished inspector UI
            return myInspector;
        }
    }
}```

Made a custom inspector script and I have a folder path similar to this

MonoBehaviour
|

Block (Abstract)
|

MovementBlock

For some reason however this inspector will not show up in my project
swift falcon
#

my ui in computer(1) and my ui in android(2)

#

what is the issue and how to solve it

somber nacelle
stark sun
somber nacelle
#

it usually helps to say where the error came from. but also you never assign to your CurrentMovement variable yet you use it in the SlideCoroutine

#

perhaps you want to use the enemyScript variable that is passed as a parameter to that method instead

ember mortar
#

why is there no mppm documentation? it says page not found

visual dagger
#

how do i make the items in player hand visible when the correct item is in the selected hotbar slot?

#

i was thinking of setting it in the SO

#

but that wont work

somber nacelle
visual dagger
#

yeah that wont work

#

anyone please help

#

i've been sat at this for like half a day

#

if anyone can just tell me if they dealt with this

#

how they'd managed to get items to show

heady iris
#

isn't that going to be a prefab you're referencing

#

I handled this by instantiating a prefab every time I needed to show an item in the player's hand, and then destroying it when the item was put away

#

you could also instantiate the item once, then just disable it when the item is put away

visual dagger
#

i was thinking of that

#

is that a good way?

heady iris
#

well, it works

#

as long as you don't need to remember any state that was attached to the item itself

#

e.g. the actual weapon shouldn't hold the ammo count if you're creating and destroying it constantly

visual dagger
#

yeah ik

heady iris
#

(or, at least, it should not be the thing that remembers the count)

visual dagger
#

im not gonna destory them

#

im just gonna instantiate it

#

and then set it active

#

better performance

#

wait idk if its better for performance

visual dagger
#

of the item in hands?

heady iris
#

right

visual dagger
# heady iris right
if(hotbarCells[selectedCell].item && hotbarCells[selectedCell].item.itemData.handPrefab != null)
{
    InventoryCell cell = hotbarCells[selectedCell];
            
    GameObject handPrefab = Instantiate(cell.item.itemData.handPrefab, holder.transform.position, Quaternion.identity);
}```
#

i cant figure out how to instantiate it in the same position

#

like usually its here

shell scarab
#

I'm trying to prevent the below situation from causing a deadlock by making the green-circled unit start moving to the next node using the following code (my parkings on it are not exact but pretty much the situation), but it doesn't seem to work in every case. I thought I'd use the dot product between the direction of the unit's position to the current node and the direction of the unit's position to the next node, and if that's under 0, then switch to the next node if it can see it, but it doesn't seem to work. All the units are on layer 6. Is something wrong with my dot product code? This is in an update loop.

if (path.TryPeek(out next))
{
  Debug.Log("Peek Success");
  if (Vector2.Dot((current - rb2d.position).normalized, (next - rb2d.position).normalized) < 0)
  {
    Debug.Log("dot success");
    if (!Physics2D.Raycast(rb2d.position, next - rb2d.position, Vector2.Distance(rb2d.position, next), ~(1 << 6), -1, 1))
    {
      Debug.Log("raycast success");
      current = path.Pop();
    }
  }
}
#

And to add clarification to the little diagram, I tried to color-code it. The circled green unit is moving to its current node, which is the orange circled unit's last node. They are all moving in the same direction, but the green circled unit got pushed past its node so it couldn't reach it.