#archived-code-general

1 messages · Page 134 of 1

marble halo
#

A switch wouldnt need health

#

Basically like these things from ocarina of time

heady iris
#

it doesn't mean the object has health

#

it just means the object can be hit

vagrant blade
#

You wouldn't make health a part of the interface. You would create something like IDamageable

#

And then handle the OnDamage function uniquely

marble halo
#

Ah ok

simple egret
#

You can ignore any parameter you're passing, in the switch implementation
Makes me think of that "adding helicopters in game dev" meme

marble halo
#

Ah interesting

#

Just thought id ask

#

So like for an enemy OnDamage would have an int amount

heady iris
#

i usually wind up making a Damage struct/class

#

it might contain a list of kinds of damage

#

or just literally be

#
public struct Damage {
  public float amount;
}
#

if I'm not quite sure what I'll need yet

ashen yoke
#

yes struct is best

#

no allocations

heady iris
#

YAGNI -- You Ain't Gonna Need It -- suggests you just make it a float until we change it later

#

but it's not much extra work to just use the struct from the start

simple egret
#

This, so if you ever need to add stuff later on, no need to go through all call sites to add a parameter

ashen yoke
#

only problem is capturing bunch of modifiers later

gray mural
#

Why does prefab that I Instantiate stay in the Scene, when Game is finished?

#

or is it always so?

ashen yoke
#

how do you instantiate it

marble halo
#

So if OnDamage(int amount) is in the interface does that mean everything that uses IDamage need an int for how much damage?

ashen yoke
#

at runtime?

gray mural
ashen yoke
#

"class is obligated to have this method verbatim"

marble halo
# ashen yoke yes

Cause a switch like that wouldnt need the damage amount since theres no health

gray mural
# heady iris where do you do this
private int textComponentIndex
{
    get => m_textComponentIndex;
    set
    {
        while (_textComponents.Count <= value)
        {
            TMP_Text newTextComponent = Instantiate(textComponentPrefab, textComponentsHolder.transform);
            _textComponents.Add(newTextComponent);
        }

        m_textComponentIndex = value;
        _textComponent = _textComponents[value];
    }
}
ashen yoke
heady iris
gray mural
heady iris
gray mural
#

how to avoid it?

ashen yoke
heady iris
#

Now, there is another option here: separate "damage" from "activation"

gray mural
ashen yoke
#

@marble halo you can drop a parameter by using _

heady iris
#

You might do that if you have many different kinds of things you "activate"

marble halo
#

ah ok

heady iris
#

so maybe you have elecrtic arrows that do electric things

#

but!

#

i like the idea of keeping it all together. so electric arrows do electric damage and turn on electric objects

simple egret
#

Hell, you can even make interfaces "inherit" from others so their methods accumulate

heady iris
#

now there is harmony.

ashen yoke
heady iris
#

wait, this is just bioshock

#

zap

gray mural
ashen yoke
#

how do you guard it then

#

Application.isPlaying?

gray mural
#

I have just written normal script as I always do

#

nothing special with Aplications in it

ashen yoke
#

completely different semantics

gray mural
#

I am writing my script as usually

ashen yoke
#

there are 2 modes, Edit mode and Play mode

#

for example if you instantiate a prefab in play mode with Instantiate it will work as you expect

#

if you do the same in editor you are creating a broken/incorrect instance

#

because while in edit mode the correct way is to use PrefabUtility.Instantiate...

#

there are a lot of cases like that

#

lots of things to keep track of

#

Destroy/DestroyImmidiate for example

gray mural
ashen yoke
#

what default

#

i asked you if you do it in play mode you said everything is outside of it

#

play mode is a state of unity editor

#

when you press the play button it switches to it

gray mural
#

oh, you mean that

ashen yoke
#

if youre doing editor tooling you have to use editor approach for things

#

and cleanly separate play/edit behaviors

#

if you mix them with ExecuteAlways for example

gray mural
crimson atlas
ashen yoke
#

default in what context

gray mural
gray mural
crimson atlas
#

you can edit during play, however it won't stay after play is finished

#

whatever edits you do during play, it only affects the play session
everything goes back to what it was before you hit play

ashen yoke
crimson atlas
#

well it might depend on what you're editing then
(i'm new here btw. asking questions mostly. lol)

gray mural
ashen yoke
#

for example you have some Awake/OnEnable in a class with [ExecuteAlways]

gray mural
ashen yoke
#

post the whole class

#

!code

tawny elkBOT
#
Posting code

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

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

crimson atlas
#

you pause play (or not), then "tab out" to edit tab, and do whatever you want.

gray mural
#

just normal class

ashen yoke
#
    [ExecuteAlways]
    [SelectionBase]
    public class Selectable 
gray mural
#

how to avoid it?

ashen yoke
#

i dont think you can avoid it here

#

but you can modify your code accordingly

#

also i dont understand why you hid virtual methods

#

instead of overriding them

#

that should most likely break the whole thing

gray mural
ashen yoke
#

yes

heady iris
#

i'm not sure how override vs. new behave with respect to unity messages

gray mural
#

why should I override them?

ashen yoke
#

so that base methods would be called

#

and your method would be called as well

gray mural
#

though maybe

heady iris
ashen yoke
#

if event system operates on selectable directly, your new methods should not be called at all

gray mural
heady iris
#

ah, fair.

crimson atlas
#

pacman game, player collider, ghost collider
which one of the two should i mark for "is trigger"?
i know i can do in any of the two, but is there a best design?

jaunty needle
#

Guys why am I getting this NullReferenceException here?

    {
        stairSpawner.SpawnedStair += IncreaseStairCount;
    }
#
    {
        stairSpawner = FindObjectOfType<StairSpawner>();
    }
gray mural
ashen yoke
heady iris
jaunty needle
heady iris
#

Awake and OnEnable are instant; Start is before the next Update

simple egret
#

Yeah, so you could move the code from Start to Awake here

jaunty needle
swift falcon
#

Can anyone help me figure out this input system code?

[System.Serializable]
    public struct TextIARPair
    {
        public TMP_Text Text;
        public InputActionReference IAR;
    }

    [SerializeField] List<TextIARPair> _textIARPairList = new List<TextIARPair>();

    InputActionRebindingExtensions.RebindingOperation _rebindingOperation;
    InputControls _controls;

    void Start()
    {
        _controls = Get<PlayerInput>().Controls;

        string rebinds = PlayerPrefs.GetString("rebinds", string.Empty);
        if (string.IsNullOrEmpty(rebinds)
            return;        

        _controls.LoadBindingOverridesFromJson(rebinds);

        foreach (var pair in _textIARPairList)
          pair.Text.text = KeybindToText(pair.IAR);
    }

    public void Save()
    {
        string rebinds = _controls.SaveBindingOverridesAsJson();
        PlayerPrefs.SetString("rebinds", rebinds);
    }

    public void StartRebinding(InputActionReference iar)
    {
        TextIARPair pair = FindPair(iar); // Gets pair from list

        _controls.Disable();

        _rebindingOperation = iar.action.PerformInteractiveRebinding()
            .OnMatchWaitForAnother(0.1f)
            .OnComplete(x => RebindComplete(pair))
            .Start();
    }

    void RebindComplete(TextIARPair pair)
    {
        _rebindingOperation.Dispose();

        _controls.Enable();

        Save();
    }

    public void ClearBindings(InputActionReference iar)
    {
        iar.action.RemoveAllBindingOverrides();

        Save();
    }```
When I change a keybind it assigns it correctly but when I leave the pause menu I cannot perform any inputs, also if I restart play mode it doesn't seem to save any of the keybinds. A lot of this stuff is going over my head tbh
swift falcon
#

When I do this I get an empty string back:

string rebinds = _controls.SaveBindingOverridesAsJson();
        Debug.Log(rebinds);```
But this returns the new overriden keybind at the same time:
```cs
string KeybindToText(InputActionReference iar)
    {
        int bindingIndex = iar.action.GetBindingIndexForControl(iar.action.controls[0]);

        string path = iar.action.bindings[bindingIndex].effectivePath;

        return InputControlPath.ToHumanReadableString(path, InputControlPath.HumanReadableStringOptions.UseShortNames);
    }```
#

So I think there's something wrong with SaveBindingOverridesAsJson() but I'm struggling to think of why

#

Although considering the fact that the overriden inputs aren't getting detected, the problem is probably there
What's wrong with this code?

// Variables
InputActionRebindingExtensions.RebindingOperation _rebindingOperation;
InputActionReference iar;

// During Binding
_rebindingOperation = iar.action.PerformInteractiveRebinding()
            .OnMatchWaitForAnother(0.1f)
            .OnComplete(x => RebindComplete())
            .Start();

// On Complete
    void RebindComplete()
    {
        _rebindingOperation.Dispose();
    }```
The problem must be within here
swift falcon
#

Ok I found out why the player was unable to move, unrelated problem. But the keybinds still aren't saving

#

Nor being applied at all

swift falcon
#

Ayy got it working, problem was with the fact that the InputAction I assigned in the inspector was different to the one I actually used for detecting input and saving/loading. I didn't realise they were different :P whoops

soft shard
rough sorrel
#

One question, is there a way to like lock the cursor to the middle of the screen/hide it but still be able to interact with world canvas elements such as buttons please?

leaden ice
rough sorrel
#

when I lock the cursor I can't use the UI

rough sorrel
ionic socket
#

I'm having an issue with the Async/Await workflow. Let's say I have methods A(), B(), and C(). Method C() is a async Task that awaits some other Task. within Method A(), there's a loop which calls B() each iteration, and within B(), a loop which calls C() in each iteration. The execution of Method C() stops when it reaches the await statement; however, methods B() and A() each complete their loop statements without waiting for the Task in method C() to be fulfilled.

If I want the await in Method C() to halt the entire chain, does that mean that A() and B() also need to be async methods that are awaited?

For cleanliness purposes, I dislike making every method in the chain an async method because it mostly doesn't ever need to await anything and I find myself adding a lot of "return Task.CompletedTask;" at the end of methods. Is there another way to go about this other than marking every thread that might be awaited downstream without converting them all to async Tasks?

steel elk
heady iris
#

it's turtles all the way down

ashen yoke
#

there is no way to "halt" a normal method

ashen yoke
#

async method is converted to a state machine

#

its literally a giant switch under the hood

heady iris
#

same for enumerators, right?

ashen yoke
#

yes

heady iris
#

every vaguely magical C# feature is just a state machine in a trenchcoat

crimson atlas
heady iris
#

you need a trigger when you need a trigger!

crimson atlas
#

i read the manual on it, but still
pacman and ghosts do not interact with each other in what physics are concerned (there is no physics simulation)
it's basically, collision = one of them goes poof
wouldn't marking as trigger make the collision cheaper or something because no physics simulation?

heady iris
#

when you want to detect things without collisions

heady iris
#

the main draw is that you don't mess with physics.

crimson atlas
#

but isn't a trigger necessarily a collider (with "is trigger" marked)?

heady iris
#

you don't run into an autosave point and bounce off

#

you just walk into the trigger zone

crimson atlas
#

but can't you make do with a collider (without a rigidbody)?

#

same thing, "OnCollisionEnter" -> save game

heady iris
#

sure

#

but then the player can't walk into the zone

#

it's a collider

crimson atlas
#

OH

#

so it's going to block stuff?
and "is trigger" makes it allow stuff through?

heady iris
#

yes

crimson atlas
#

didn't realize a collider was going to block stuff unless it had a rigidbody

#

so no rigidbody necessary to block stuff then?
no idea why i always assumed you needed a rigidbody to block

heady iris
#

colliders are colliders

#

having a rigidbody is necessary to be affected by physics and to receive collision events

#

One of the two objects must have a rigidbody to receive any physics messages

crimson atlas
#

wait, on "to receive collision events"

#

can you give me an example of a collider interaction that requires a rigidbody?

heady iris
#

well, to start

#

if you have two objects with colliders, and neither has a rigidbody

#

collisions don't really matter

#

they ain't moving

#

if you manually move them into each other, you won't get collision events

#

OnCollisionEnter, for example

crimson atlas
#

hmmm now it starts to make sense

heady iris
#

One of the two must have a rigidbody for these messages to be sent

steel elk
#

Rigid body = something to be controlled by physics, things without it but with colliders are essentially static objects that can be run into

crimson atlas
#

but pacman and the ghosts don't need rigidbodies to be implemented do they?

#

i mean i'm not going to use any physics simulation to move them around

heady iris
#

They can use a kinematic rigidbody

crimson atlas
#

how can i implement the object "touch" or "overlap" detection?

heady iris
#

Kinematic rigidbodies are still understood by the physics system

#

But they aren't affected by physics

lean sail
#

you can detect if they overlap by other means, but might as well still use collision events

crimson atlas
#

so i can't actually code "touch" events without rigidbodies in the end?

#

i mean with the given tools, not having to resort to coding my own

#

talking about colliders, rigidbodies, triggers etc etc

#

and the "oncollision" "ontrigger" events

heady iris
lean sail
#

Yes u need a rigidbody, otherwise your object isnt really supposed to move and collide

latent latch
#

it's funky but something needs a rigidbody, but like that rigidbody can be kinematic

heady iris
#

It's fine if you aren't making the player be affected by physics

#

like, the player doesn't get pushed around

crimson atlas
#

now i'm confused as to why make colliders and rigidbodies separate thigns

heady iris
#

although, a kinematic rigidbody also ignores collisions

heady iris
#

a rigidbody is what makes you into an object that gets pushed around by physics

crimson atlas
#

so the collider is basically the shape of the rigidbody?

lean sail
heady iris
#

it's the shape of the object

lean sail
#

a rigidbody has no shape

echo plaza
#

Hey there, I'm wondering how I could go about adding a planting mechanic for my game. More specifically, I have a few things I want to try and do.

First, I want to create a box collider that would go around the entire plant model, which is made up of multiple gameobjects. Next, I'd want to apply a material to both the parent model and all of its children.

steel elk
#

It's worth considering that if you're using a physics engine for a Pac-Man clone you might be bringing an automatic shotgun to a knife fight

crimson atlas
#

if i have a collider (no rigidbody) setup, and another collider (with rigidbody) touches it, will it stop moving (and be blocked) by the no-rigidbody collider?

ashen yoke
#

best to think of a collider as just a collider

#

its just a physics shape

#

you can have 10 colliders representing a single "object"

#

object in this case is some abstraction, like a mesh

crimson atlas
#

let me see if i'm starting to understand it better

heady iris
lean sail
ashen yoke
#

rigidbody treats a group of colliders as a physical object

#

you can have many colliders under the same rigidbody and they will act as a single physics object

lean sail
#

the only slightly annoying part about many colliders is dealing with which one got hit

ashen yoke
#

that is solved through relaying events to the root

lean sail
#

if that matters for your game

crimson atlas
#

so an object with a collider and no rigidbody would be better suited to serve as a boundary or a no-physics wall of some kind?
whereas if i mark it as "is trigger" i transform that same objecti with collider but no rigidbody in a penetrable/traversable "area" (instead of a wall) that will send "ontrigger" events?

ashen yoke
lean sail
#

yea its easily solved, i just dont like having a script on each child object. Maybe its different for me, i got 18 colliders :p

ashen yoke
#

a floor collider doesnt need a rigidbody, it doesnt move

#

but physx still uses it to compute collisions for rigidbodies

crimson atlas
latent latch
#

If you want to ignore rigidbodies completely, just cast (sphere/box) yourself. You wouldn't use OnTriggerEvents but rather your own methods.

crimson atlas
#

i'd like to use the stock functions as much as possible, especially to actually learn them

latent latch
#

You'd have more control on when to check as well which is a plus

crimson atlas
#

i've published a game (shocking right) using all of that but without understanding 20% of it

#

what if i have an object+rigidbody with a collider set as "isTrigger"
how would such a monster behave?

lean sail
#

Like you can close and open a door without putting a rigidbody on it

crimson atlas
lean sail
#

as for the triggers, u can use them however u want really but yea its more so detecting if something entered an area, or just left the area

crimson atlas
lean sail
#

a trigger is different, your rigidbody would essentially just fall through the floor

latent latch
#

Rigidbodies are mostly for using unity's physics, not primarily a focus (more of a subset) on the collisional aspects, but there is some functionality that it introduces that does help against faster projectiles

crimson atlas
#

do rigidbodies not need colliders in order to collide (to stop, be stopped or physically interact) with other stuff?

lean sail
#

if you give your rigidbody a collider AND trigger, you can use the trigger to detect if things are within your trigger area for example. Like if you had items to pickup from the floor, you dont want to calculate the distance between yourself and every item. You would rather have a trigger that can detect if an item entered its bounds

#

triggers just have a different use

crimson atlas
lean sail
#

yea

crimson atlas
#

so marking a collider as a trigger transforms it into something else entirely i guess?

#

i mean, it stops being a "collider" since it won't collide with anything anymore?

#

it's just detect overlaps (ontriggerenter)?

lean sail
#

I guess you can word it like that yea. One of the 2 objects still needs a rigidbody though

#

also 2 triggers cannot collide

lean sail
heady iris
#

This is wrong. The "colliders overview" page contradicts that

#

I think it was true at one point...

#

i remember reading about people complaining about it

lean sail
#

ah i once again fell for the misleading wording

heady iris
#

i'm pretty sure the page is asserting that no messages get sent

#

The same applies when both GameObjects do not have a Rigidbody component.

#

this is true: no trigger messages get sent

lean sail
#

UnityChanThink english is hard

crimson atlas
#

wait

#

so it's actually impossible to implement "pacman eats ghosts" without rigidbody, be it with OnCollisionEnter or OnTriggerEnter
since any will require at least one rigidbody?

heady iris
#

Yes. If you want collision events, you must have a rigidbody on at least one object

#

end of story.

#

Having a rigidbody does not mean that the object is affected by physics

#

it can be kinematic

#

kinematic rigidbodies are not affected by forces

#

you just have to move them with Rigidbody.MovePosition instead of setting the transform's position directly

#

that's all

crimson atlas
#

hm gotta check my old game source

#

pretty sure i just use translate

heady iris
#

that might work, sometimes

#

the problem is that this moves the object without letting the physics system handle it

#

it might be ok

crimson atlas
#

but yeah a rigidbody and colliders (and triggers) to implement a "one object goes poof" on "touch"

#

it's the game snake basically, but with smooth movement

#

i move the snake with translate and rotate purely, no force stuff, it's a top down 2d game

#

when snake "mouth" collider enters the "fruit" trigger collider, fruit gets eaten

#

snake grows

#

i remember i (had to) put a rigidbody in the mouth object

#

had to or it wouldn't trigger iirc

#

that's so weird to me thogh. not sure if i'm making sense.

#

i mean, there are no physics anywhere.
why do i have to place a rigidbody in order for the game to detect the "touching" or "overlapping" of two areas (colliders in this case)

crimson atlas
#

hmm. seems i'm probably looking for a "kinematic"-rb-snake and a "static"-rb-fruit
it's probably how unity would want me to do this

heady iris
#

yes

crimson atlas
#

however i'm not sure i wanna use MovePosition and MoveRotate.

#

i don't want forces, i'm specifying how many pixels i want it to move, and i'm controlling velocity by script

heady iris
#

Those are not forces.

#

MovePosition sets the position

crimson atlas
#

oh then that's awesome

crimson atlas
#

so it teleports, but collides along the way lol?

heady iris
#

if you're using continuous collision detection, yes

crimson atlas
#

omg i'm going to have to rewrite my whole snake body movement script
it was just a list of transforms.
i guess it's about to get a lot more complicated

#

collider and otherCollider is SO unintuitive
collider refers to the OTHER
and otherCollider refers to myself?
is it really like that or i'm missing something?

#

snake script's OnCollisionEnter's collision.collider returns info about the fruit's collider?
and collision.otherCollider returns info about the snake's own collider?

crimson atlas
#

lol something's definitely wrong

simple egret
#

.collider is the other collider (the object you collided with)
Then once you get a contact point, there's .thisCollider (yourself) and .otherCollider which is like the Collision's collider property above

crimson atlas
#

but collider and otherCollider are giving me different results, they're behaving invertedly

jaunty needle
crimson atlas
#

hmm i wonder if that might be happening because i'm using transform.translate to move them (and not MovePosition)

simple egret
#

Probably

jaunty needle
#

A nullreferenceexception

simple egret
#

A collision can have multiple contact points

jaunty needle
#
    {
        stairSpawner.ReachedEnd += EndGame;
    }
#

oop

#

sorry my bad

#

same solution

crimson atlas
#

doesn't give me the "thisCollider" option

simple egret
#

Ah I was looking at the 3D Collision class, which is different hang on

crimson atlas
#

head = sickles
the yellowish ball above and behind it = resource

simple egret
#

Yeah seems like otherCollider is yourself, docs are not easy to read on that

crimson atlas
#

the names used are not intuitive

simple egret
#

"the incoming collider" - well both colliders are "incoming", it's relative

crimson atlas
#

besides it's inconsistent with how the 3d version works i guess

simple egret
#

As for the thisCollider and otherCollider, you need to get a contact point for that using GetContact(), they're not on the Collision2D itself

#

Great, for 2D they're not named the same as for 3D!

#

ContactPoint2D's thisCollider is just collider

lusty dune
#

Why don't you use collision.tag == tagname ?

crimson atlas
simple egret
#

Actually, no, it's the collider of the other object

crimson atlas
#

exactly

#

that's where the confusion resides and it's really unintuitive

simple egret
#

otherCollider is yourself, wtf were they on when they decided on the naming

crimson atlas
#

see what i'm saying

#

tried to google "unity collider otherCollider inverted" but no luck
i refuse to believe nobody ever saw that
i'll take some time to write something on discussions and see what people say

unreal island
#

I'm trying to move my project from editing in windows to linux. I have Unity 2022.2. When I opened the unity editor to the project in ubuntu I got a huge number of errors all saying that GraphicsFormat.R8_UInt (I'm trying to set a RenderTexture.stencilFormat) is unsupported. However when I look online I see this suggested as the most commonly supported format (https://docs.unity3d.com/2022.2/Documentation/ScriptReference/RenderTexture-stencilFormat.html).

How can I figure out what formats I can support / is there anything I can do to make this format supported?

unreal island
#

Thanks sorry

crimson atlas
#

i think i've solved the mistery on "collider" and "otherCollider" naming choices

#

at some point in the past there was no "otherCollider" (it isn't hard to referece one's own collider to get info)
it was just "collider" and refered to the "other guy"

#

then they implemented "otherCollider" but left "collider" referring to the other guy (and otherCollider to oneself) so people wouldn't need to rewrite code or something

#

only reasonable explanation

woeful spire
#

I'm rotating object's localRotation in code. The snippet looks like this.
transform.localRotation = Quaternion.Euler(stopAngleAdd, transform.localRotation.eulerAngles.y, transform.localRotation.eulerAngles.z);
the stopAngleAdd just has the value 8.
When doing this the objects stop either at 8, 0, 0 in rotation (which is what I want)...
Yet other ones stop at 172, 0, 0...
I noticed this is 180 - 8, which is the same value as stopAngleAdd, so I guess I'm missing something with Quaternion.Euler?

#

the objects could have any degree on the x-axis when the snippet is run, so we never know from what rotation this is done.

golden vessel
#

Hey, can I reinitialize an array? Will it keep the previous elements if I make it bigger? Or should I just use another array?

woeful spire
#

this way the length is variable.

golden vessel
#

Hmm let me think maybe I'm going about this wrong to begin with.

quartz folio
woeful spire
quartz folio
#

More like: 90, 0, 0 might be the same as 0, -90, 90 (please don't test this, it's just an example)

#

Which is why constructing a rotation from incomplete individual portions of a euler angle that was derived from the internal quaternion is a bad idea

#

if you're doing this sort of thing it's generally better to keep track of your own individual rotation values and apply them to the transform

#

instead of reading back from the transform and hoping the representation in eulerAngles is what you expect

golden vessel
#

Why are EulerAngles used for to begin with? Idk much about it but I'm pretty sure you need only two variables to completely define an angle right?

quartz folio
#

What do you mean? They are the rotations around X Y and Z

woeful spire
quartz folio
#

They are only used for authoring and utility purposes, and in some specialised places like animation

golden vessel
#

Well you need only 3 variables to define any point in space from what I remember

#

But distance shouldn't really matter

#

If you're interested in angles only

#

You can go (x,y,z) or (r, phi, theta)

quartz folio
quartz folio
#

It's because they don't suffer from gimbal lock

#

They also interpolate directly instead of having weird axis problems

golden vessel
#

ok thanks for the explanantion, I'm going to google those words 😄

woeful spire
# quartz folio I'm not sure what your complete setup looks like, but I recommend keeping track ...

Okay, I see. I'm only interested in changing the x-axis's rotation of the object, but I still need to keep track of the other axes to make sure they don't "interfere" with my x-axis-number as it might be interpreted differently if the Z and Y values are strange.
Does that make half-sense the way I wrote it?
I think this makes sense as it goes back to "90, 0, 0 might be the same as 0, -90, 90"-kinda deal. Yes?

quartz folio
#

Yes, that is likely your issue

#

Another option is to use a compound transform that only applies a rotation in that one axis so you don't have interference from the other rotations

woeful spire
quartz folio
#

Just having another transform under this one

#

Two transforms in the hierarchy instead of one

woeful spire
neat echo
#

is there a simple solution to outlining the voxel that a player is looking at if all the voxels make up a single mesh?

#

if each voxel was its own mesh then that'd be a lot simpler but they're all a part of one big mesh

#

i just wanna know if theres a simple way to deal with this or if its gonna be way outside the scope of this project

tiny mantle
#

!code

tawny elkBOT
#
Posting code

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

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

neat echo
#

i should clarify: i want to highlight just the face that the player is looking at

tiny mantle
#

why isn't this spawning the grass where i need it to, the grass tile needs to spawn anywhere between the last tile and 3 tiles in front of it https://gdl.space/elubicayet.cs

crude mortar
#

you can get the correct position by rounding then adding an offset, and then just set the forward of the sprite to be the hit.normal

#

by sprite I just mean something like this

gray mural
#

How do I "name" methods like Awake, Start, OnGUI, Update, LateUpdate etc.?

#

yes, this kind of questions one more time

fervent furnace
#

you cannot name them to other name
i heard that unity engine find these methods through reflection

quartz folio
real sequoia
#

!code

tawny elkBOT
#
Posting code

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

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

gray mural
#

"Source Methods" ?

quartz folio
#

Unity messages

gray mural
quartz folio
#

Message functions, whatever you want to call them, include the word message and people will probably know what you mean

gray mural
quartz folio
gray mural
#

thank you

real sequoia
#

I have a score manager script that increases the score based on height difference. It's working as expected, but instead of increasing the score in the Update function, I want to create an event. I know how to create an event, but I need suggestions on how to trigger that event. For example, in a coin-based score system, touching the coin triggers the event and increases the score. I want to implement a similar concept in my game. Any suggestions or examples would be appreciated.

#
using UnityEngine;

public class ScoreManager : MonoBehaviour
{

    #region Variables

    [SerializeField] private Transform player;

    // Example - If the scoreIncrementHeight is 2, it means that if the player moves up by 2 meters or 2 grid units, their currentScore will increase by 1.
    [SerializeField] private float scoreIncrementHeight = 2f;

    private float lastRecordedPlayerHeight;

    private float currentPlayerHeight;

    private int currentScore = 0;

    private int highScore;

    private const string HIGHSCORE_PLAYER_PREFS_KEY = "high_score";

    #endregion

    private void Start() {

        currentPlayerHeight = lastRecordedPlayerHeight = player.position.y;

        highScore = PlayerPrefs.GetInt(HIGHSCORE_PLAYER_PREFS_KEY);

    }

    private void Update() {
        IncreaseScoreLogic();
    }

    void IncreaseScoreLogic() {

        currentPlayerHeight = player.position.y;

        float heightDifference = currentPlayerHeight - lastRecordedPlayerHeight;

        if (heightDifference >= scoreIncrementHeight) {

            lastRecordedPlayerHeight = currentPlayerHeight;

            currentScore++;

            // High Score
            if (currentScore > highScore)
                SetNewHighScore();

        }

    } // IncreaseScoreLogic

    void SetNewHighScore() {
        highScore = currentScore;
        PlayerPrefs.SetInt(HIGHSCORE_PLAYER_PREFS_KEY, highScore);
    }

} // Class
```cs
gray mural
#
// e.g. your ScoreManager class

private int _currentScore;

private void OnEnable() => CoinCollector.OnCoinCollected += CollectCoin; // + on enabke

private void OnDisable() => CoinCollector.OnCoinCollected -= CollectCoin; // - on disable

private void CollectCoin(int value) => _currentScore += value; // do when collecting coin
real sequoia
#

Thank you for the quick response. What you share is also i found on google but in my game score gets increased based on height difference in that case how to trigger an event

private void Update()
{
    currentPlayerHeight = player.position.y;

    float heightDifference = currentPlayerHeight - lastRecordedPlayerHeight;

    if (heightDifference >= scoreIncrementHeight)
    {
        // Trigger the event here
    }
}

But in this case, using event is no good because what i am doing before is same as this

real sequoia
#

I don't want to put my increase score logic in Update, that's why I am using event to make my score manager optimize.

real sequoia
gray mural
gray mural
#

oh, I see

gray mural
#

do you still need to trigger in in OnTriggerEnter?

#

or just within Update?

fervent furnace
#

unfortunately you have to do it in update to continue check whether the new input data is > than old record

real sequoia
gray mural
gray mural
real sequoia
real sequoia
lean sail
#

atwhatcost what if you have a trigger placed so the bottom is at your previous highest point, then anytime you are within the trigger, send the trigger higher

real sequoia
#

I also heard inside FixedUpdate only put physics related logic

fervent furnace
#

now the physics engine have to keep track the one more collider and fire the event if you touch it

lean sail
#

Therefore it's the physics engines problem, not mine

lean sail
fervent furnace
#

you just throw the workload from your logic to physics engine in Fixed update....

real sequoia
fervent furnace
#

i just reply to the idea of using collider
the problem is wherever you put it you "optimize" it by changing it sampling interval

real sequoia
#

Got it. But I am little bit confused with Fixed Update function, can I put other logics which are not related to physics inside Fixed Update?

fervent furnace
#

you can

real sequoia
#

Is this a good way? Everyone does it?

fervent furnace
#

if your logic need to sample in constant time interval then you may want to put it in fixed update
but apart from physics i cant come up with other example

real sequoia
#

Thank you everyone for your quick responses.

lean sail
#

but most of it is eventually used for physics

real sequoia
#

Got it.

valid trench
#

hi im trying to make a platform fighter (similar to smash bros) and i was making the knockback functionality.
according to the wiki, this is the knockback formula used in the game. what is this function exactly returning? how can i apply knocback based on whatever this function returns? do i just multiply the value to my velocity? i did try that but it didnt really work. also how can i get the angle for the knockback and stuff too?

lean sail
valid trench
#

i have an understanding of what the variables are

#

i just dont know what value im getting

#

like

#

what im supposed to be doing with it

#

thats the link

lean sail
#

the value returned is just a number, so they likely have an angle they apply this force at

valid trench
#

my idea of the angle wwas

lean sail
#

the angle used seems almost arbitrary, it says it depends on the players gravity but thats likely just due to the formula

valid trench
#

transform.position of the player getting attacked - whatever the centre of the attack collider is returns the direction

lean sail
#

u probably have to make it up per move tbh

valid trench
#

and then for angle i saw some thread doing something like this

lean sail
valid trench
valid trench
#

how else can i do this then?

#

get the angle i mean

#

like the angle where the player is supposed to be launched towards

valid trench
lean sail
#

I dont know much of how the game works, I really would just make up an angle depending on the move. At least this way, moves will consistently launch in a certain direction

valid trench
#

what im tyring to get is

#

wait let me draw this somewhere

#

ok this is confusing but the idea is

lean sail
valid trench
#

blue is the player getting hit, red is the attacking collider, and green is the direction the player gets thrown toward

lean sail
#

the green would be like 45 degrees then, thats really all. You just associate some angle to moves

valid trench
#

i see

#

wait i watched this video ill timestamp it

#

one sec

lean sail
#

this seems more like something u need to watch more than me :p

valid trench
#

i dont really understand how they get that exact angle

#

like where they derive it from

lean sail
#

some parts of the wiki you linked still leads me to believe these angles are predetermined, but either adjusted or the force is adjusted based on factors

valid trench
vernal plank
#

why
var folders = AssetDatabase.GetSubFolders("Assets/Silex-Materials_Pack/Textures");
with Debug.Log(folders); returns nothing System.String[]
while trying to print one element of the array returns it ?

#

can you print the whole array without looping

lean sail
valid trench
#

thats like

#

the sakurai angle or something

#

so like

lean sail
valid trench
#

idrk much about it but the general idea i got is that they first derive the angle, and then perform some sakurai angle thing based on that initial angle and the knockback from the attack

lean sail
#

Just saying i have no clue what sakurai angle means

#

and i dont really intend to learn

valid trench
#

yeah i dont either lmao

#

know what it means

#

alright ill try taking a look at the wiki again and let you know if i get somewhere

lean sail
#

really for your game, just getting something working is better and then try to adjust it

#

you dont need to make a smash clone. And not many people are gonna notice your angles dont 100% line up to their calculations

#

Predetermined angle + adjustment due to weight, place hit at, force, and health are perfectly fine

buoyant crane
# valid trench idrk much about it but the general idea i got is that they first derive the angl...

very likely the angles are hard-coded per hit box (exception is the sakurai angle which has some conditions) https://www.ssbwiki.com/Hitbox

SmashWiki

A hitbox or collision bubble (sometimes hitbubble) is the main structure for how attacks are executed in most fighting games. Attacks have one or more hitboxes associated with them, and when these hitboxes overlap with a target's damageable area (often called their hurtbox or hurtbubbles), the attack is considered a hit. Hitboxes are invisible a...

valid trench
#

i see

earnest gazelle
#

Hey, one question, typically in voxel based games, how are voxels selected for example for digging?
It is an isometric game but the camera can rotate
Screen space (2d rect) or world space? A player presses the mouse button and drag it, then drop.
I would say screen space. What do you think?
In 3d model softwares like Maya, it is screen space by default.

tropic otter
#

hi, sorry for asking

#

did anyone know how to connect an external nfc reader to unity?

hushed needle
#

hi, is this code correct for a 2D game?

gray mural
tawny elkBOT
#
Posting code

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

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

buoyant crane
rain junco
#

Hey so i have a little Problem, if i write something with Input.touches it doesnt do it. Anything that has this in it for ex. Debug.log it doesnt do it and i didnt find anything about it

gaunt blade
#

hey, so something really confusing is happening

#
        {

            float prevAngle = 0;
            for (float i = 360/steps; i <= 360; i=i+360/steps)
            {
                Vector2 vertex1 = new Vector2(this.radius * Mathf.Sin(prevAngle), this.radius * Mathf.Cos(prevAngle));
            }
        }```
#

For some reason, it's not recognizing the multiplication operator within the Vector2 object instantiation.

#

And so it's throwing an error instead of doing multiplication

#

Anyone know why this might be the case?

#

The code for the entire class is this:

    {
        private Vector2 center;
        private float radius;

        public Vector2 getCenter() { return center; }

        public float getRadius() { return radius; }

        public void render(float lineWidth, float steps)
        {

            float prevAngle = 0;
            for (float i = 360/steps; i <= 360; i=i+360/steps)
            {
                Vector2 vertex1 = new Vector2(this.radius * Mathf.Sin(prevAngle), this.radius * Mathf.Cos(prevAngle));
            }
        }
        public Circle(Vector2 center, float radius)
        {
            this.radius = radius;
            this.center = center;
        }

    }```
#

I really don't see a reason that it'd struggle to identify the multiplication operator.

#

Actually nvm, I just restarted visual studio and it fixed itself. Weird bug with the IDE ig?

royal pulsar
#

how do i decide between a behaviour tree and a state machine? is it simply an issue of complexity? I have a simple AI that at this point will only roam and chase the player upon line of sight.

cold parrot
swift falcon
#

Error: I keep getting the error parsing infinity while selecting a random string from my json array, It does this at random and I have no idea why. I have a temporary fix at line 49 but it is making the scene restart multiple times and is just not pleasant one bit

Snippet:``` void Start()
{
_openAI = new OpenAIApi(openAIKey);

    _client.DefaultRequestHeaders.Add("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{uberDuckKey}:{uberDuckSecret}"))}");

    // Pick a random topic
    List<string> topics = JsonConvert.DeserializeObject<List<string>>(
        File.ReadAllText($"{Application.dataPath}/Scripts/topics.json"));

    blacklistPath = $"{Application.dataPath}/Scripts/blacklist.json";
    blacklist = JsonConvert.DeserializeObject<List<string>>(File.ReadAllText(blacklistPath));
    topics.RemoveAll(t => blacklist.Contains(t));

    string topic = topics[_random.Next(0, topics.Count)];


**Full Code:** https://paste.ofcode.org/QYQsqkuvYuU9JgFf8vsGGS
quartz folio
#

@swift falcon don't cross post.

crimson atlas
#

can i group my events under a dropdown like PlayerInput has its events grouped under the "Events" dropdown?
just for the sake of tidyness?

lament grove
#

is it possible to detect a specific collider from a gameobject by the material name with collider.sharedMaterial.name, or should i be using something else to detect that specific collider? As there is a main collider for collisions and a collider that should only work to be detected by other specifical collider.

vernal plank
#

How do i get a string[] of all textures given the folder path

gray mural
vernal plank
#

fixed

#

yeah @gray mural indeed

gray mural
#

.png probably

vernal plank
#

why cant recognize Directory

#

sec

gray mural
#

it should be shown when you press Alt + Enter

vernal plank
#

is it local path or absolute path

gray mural
#

I guess both should work though

vernal plank
#

NullReferenceException: Object reference not set to an instance of an object

gray mural
#

I guess no.

vernal plank
#

it is but its not from the system

#

ill try absolute one

gray mural
gray mural
vernal plank
#

i dont have windows i can get the path from terminal thanks 😄

knotty sun
vernal plank
#

okay lol its not giveing me any line number i guess

vernal plank
knotty sun
#

it will be

gray mural
gray mural
#

make sure it exists

knotty sun
vernal plank
#

Thanks the path was missing / at the end

gray mural
vernal plank
#

i read your comments

#

and i was checking the path lol

gray mural
vernal plank
vernal plank
gray mural
vernal plank
#

appreciate your help : D

#

not sure why @ to be read as path ?

#

am on linux

gray mural
vernal plank
#

/home/larsitsmeash/Ash-lib/

dark knoll
#

I have a ScriptableObject that contains some properties that are used in game. When I change the values in the inspector, it seems all fine. When I deselect and select it again, all values are back to what they were before I changed anything. And they are not reset to their default values, just some values I used a while ago. Currently it's impossible to change the property values now. It just always resets back. Any idea what could cause this?

vernal plank
#

linux doesn't have // as far as i know

#

but noted

#

ill add it to my notes

gray mural
simple egret
#

Yeah it's a C# feature called verbatim string, that ignores escape sequences like \n or \\ so paths are easier to make

gray mural
#

and yes, I meant \

knotty sun
gray mural
vernal plank
#

linux is much smoother

knotty sun
#

windows uses backslash which is treated as a special character, linux uses forward slash which is not

vernal plank
#

when it comes to paths and directories

simple egret
#
@"a\b\c"
// same as
"a\\b\\c"
knotty sun
gray mural
gray mural
knotty sun
vernal plank
gray mural
knotty sun
#

MacOs is linux with a custom GUI

vernal plank
#

even tho mac is not linux both they are unix based

#

so they are pretty much have the same terminal and same structure but macOS is locked

gray mural
vernal plank
#

or in a better world mac is more restrictive

gray mural
vernal plank
#

Well Linux is Unix-like
And Mac is Unix based

#

this is so confusing lmao

gray mural
vernal plank
#

once you get used to it yeah
when you starting out its pure pain

gray mural
#

everything is actually for Windows.

#

every video, tutorial or docs

vernal plank
#

once you get used to it you would never go back to windows

#

unity seems fine on linux

#

never had an issue

#

i also use unreal godot

#

zbrush

#

substance designer

gray mural
#

Scratch too?

vernal plank
#

what ?

gray mural
gray mural
vernal plank
#

ill look it out
btw you can try linux on a live USB env

gray mural
vernal plank
#

before you even install it

gray mural
vernal plank
#

you dont have to install it as your daily driver to try it you can get a USB stick and boot your system from it

vernal plank
#

if you ever wanna try it hit me up you can add me too

#

id love to help back

gray mural
urban marsh
#

Hello everyone !
I am trying to code a script that would put a UI element A at the same position and size as another element B which is elsewhere in the hierarchy.
I tried changing the transform.position, including before/after changing parents, but I can not manage to get a good result.
Anybody knows how to handle that ?

dark knoll
#

Each time I deselect my ScriptableObject asset it reverts all changes to properties back to what they were before. I never had this issue before, what could it be?

#

In fact I can only change the values by editing the .asset file in a separate texteditor now...

leaden ice
#

And explain which things you are trying to change

night sparrow
#

i have a question in unity's editor.
say i have abstractclass base, and said class have 3 classes that implement it: class1, class2, class3.

i have another script which has public base variable
is it possible in the editor to assign class to variable

dark knoll
#

Short version of it (it has quite a lot of properties):

[CreateAssetMenu(fileName = "settings", menuName = "Settings")]
public class Settings : ScriptableObject
{
[Tooltip("What temperature will be tundra.")]
[Range(0f, 1f)]public float TundraThreshold = 0.3f;
}

If I change this value in the inspector, for example to 0.2, when I deselect the asset, it will just revert it back to what it was before, no matter what.

#

I must say I'm pleased I can at least change it by just editing the asset in a txt editor, I was going nuts before I realized that simple solution

night sparrow
simple egret
#

Without making a custom inspector for your Whatever class, you can't. Unity doesn't support polymorphic serialization

craggy veldt
#

you can use SerializeReference for this

mossy snow
#

another option is to make your base class a ScriptableObject, and all your subclasses will have to be assets

night sparrow
mossy snow
#

Why not? It's data, and he won't have to create an inspector or do anything hacky to choose his variable

night sparrow
mossy snow
#

SerializeReference has never worked well for me, if it's simple you can use my suggestion, otherwise you might as well use something like odin

craggy veldt
craggy veldt
mossy snow
#

I strongly suggest you try and use it first. Their example is janky for a reason

craggy veldt
#

been abusing it for awhile now 😄

#

it's splendid

night sparrow
craggy veldt
#

bruh

night sparrow
#

?

craggy veldt
#

are you sure you read the docs properly?

#

[serialiazereference] Base baseClass = new FirstClass()

hushed needle
#

Hi, I'm currently watching a video to implement the A* algorithm in unity, my game is a top-down 2d map (like enter the gungeon) but his game is a top-down 3d map . he Wrote a code to adjust the weight of each grid(like, in snow you are much slower than flat surface) which doesn't work for me because I can't do the same in 2D. Any idea how to do the same in 2d? his code:

fervent furnace
#

i use physics2d.overlapcircle

heady iris
#

If so, you can convert a world-space position to a grid-space position.

#

(and then find the tile for that grid-space position, if one exists)

#

or is this not tilemap-based?

hushed needle
heady iris
#

can you take a world-space position and turn it into a grid-space position?

hushed needle
#

i have a method for this

heady iris
#

then you just need to figure out which grid space you're on and then get the tile at that space

#

no need for physics at all

hushed needle
heady iris
#

your question is "how do I find the tile at a certain position?"

#

you don't need to do any raycasting for this. you already have a regular grid of tiles.

hushed needle
heady iris
#

Then I'd suggest implementing that.

#

It's very important to be able to convert back-and-forth between world and grid space.

hushed needle
heady iris
#

Right.

#

You want to know what kind of tile is present at that spot

#

so you might need to go A* grid -> world space -> drawing grid

hushed needle
#

lol

#

thanks

heady iris
#

i mean, it's your grid :p

gray mural
#

Is it possible to make myProperty.Length return whatever I want ?

#

myProperty is obviously a string property

heady iris
#

.Length will be a property from the string

#

maybe you can derive from the string class and override the .Length property? sounds weird

gray mural
heady iris
#

you'd have to return your own modified string type

gray mural
#

for example

private string foo
{
    get => bar;
    set => foo = value;
}

// foo = "fdsfsdfsdfsdfs"

// foo.Length; // returns e.g. 0 
knotty sun
heady iris
#

string is a sealed type

#

what are you trying to accomplish here

gray mural
heady iris
#

the non-printing space character?

gray mural
heady iris
#

when the string is nothing but a zero-width space?

heady iris
#

are you trying to count visible characters here?

gray mural
#

I need it to return 0 when it's "\u200B", otherwise just normal Length

#
...

if (value.Length == 0)
    value = "\u200B";

_textComponent.text = value;

...
heady iris
#

perhaps you can just keep value as an empty string

#

and then set the text component to contain a zero-width space anyway

gray mural
#
private string text
{
    get => _textComponent.text;
    set
    {
        if (value == null)
            value = string.Empty;

        value = value.Replace("\0", string.Empty).Replace("\u200B", string.Empty);

        _caretPosition = value.Length;

        if (value.Length == 0)
            value = "\u200B";

        _textComponent.text = value;

        AlignCaret();
    }
}
#

anyway, how do I override Length, as you have mentioned earlier?

simple egret
#

You can't, you're better off using an extension method (cannot make extension properties in C#) that returns your desired length, and call that one instead

heady iris
#

oh, true, extension methods would help here

#

you just couldn't clobber the original property (even if you had extension properties)

gray mural
heady iris
#

yeah, there you go

#

of course, what if the user wants to enter a zero width space? :p

gray mural
gray mural
#

zero width space does not exist on keyboard

heady iris
#

well, sure, but neither do emojis

gray mural
#

and user cannot copypaste in my input field

gray mural
heady iris
#

ah yeah, if you can't even copy paste, then i guess it's not relevant

#

I just think it's good to not have any "special" strings

#

it'd be nicer to have a flag that tells you if the field is empty

gray mural
heady iris
#

ah, so you need to have something in there

gray mural
heady iris
#

i mean you would still have a zero-width space in there; the "text" property would just be an empty string

gray mural
#

I don't think I should seperate them somehow

#

and that's exactly what TMP_InputField uses

#

I have been investigating their code

#
m_TextComponent.text = processed + "\u200B"; // Extra space is added for Caret tracking.
crimson atlas
#

!code

tawny elkBOT
#
Posting code

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

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

crimson atlas
#

why does Vector2.up, in the context of transform.translate gives me a "local" up (that points to the forward direction my transform is facing), but in the context of rigidbody.MovePosition gives me a "global" up (that points always "up" regardless of my transform's rotation)?

small trench
#

It's transform.up that will give you the local y axis of the object

leaden ice
jaunty sleet
#

Hey guys, I have a script in my game called rhythm cube. I have a list of references to the copies of the script on my objects in the scene. I use this code: foreach (RhythmCube cube in rhythmCubes)
cube.StopAllCoroutines(); To try and stop all the coroutines the scripts are running, and it doesn't work. Any ideas?

leaden ice
leaden ice
#

It's simply just because that's how they wrote Translate

jaunty sleet
#

It doesnt stop the coroutines. I can see that they are still running after this code has been triggered

crimson atlas
leaden ice
leaden ice
#

there's a Translate overload that allows you to tell it whether it's local or world space

#

read the docs

#

MovePosition is always in world space

small trench
crimson atlas
#

yeah i just did.
i was wondering if there's a classier way of achieving the same result but with MovePosition (to still process the physics stuff etc)

leaden ice
#

What uv said

crimson atlas
#

but if i use transform.up won't it not do physics stuff (collider/rigidbody)?

#

i was told to use MovePosition instead of transform.Translate exactly for that reason

leaden ice
#

unless there's some other coroutine involved

jaunty sleet
#

Oh, that makes sense

#

I guess the coroutine doesn't have to only run on the script its code is from

leaden ice
#

In other words - replace:

        foreach (RhythmCube cube in rhythmCubes)
            cube.StopAllCoroutines();```
with:
```cs
StopAllCoroutines();```
jaunty sleet
#

thanks

crimson atlas
leaden ice
leaden ice
leaden ice
#

it's just data

#

it doesn't do anything

#

you were told to use MovePosition instead of Translate

#

and that's still true

leaden ice
# crimson atlas

note that you can and probably should replace this code with:

rigidbody.velocity = transform.up * moveSpeed;```
#

MovePosition doesn't actually respect collisions properly

#

especially if this object is dynamic

crimson atlas
#

no need for the deltatime stuff in this case?

quick elbow
#

Should I use a CharacterController or RigidBody for an FPS game with vaulting, jumping, etc. Or is this simply a matter of personal preference?

small trench
leaden ice
#

velocity already is a per-second quantity

leaden ice
#

MovePosition is much more disruptive to physics calculations than setting velocity

crimson atlas
#

it' kinetic btw. all manual move

small trench
#

Yes should always be using AddForce for non kinematic bodies

leaden ice
crimson atlas
#

wow it worked flawlessly

leaden ice
small trench
small trench
crimson atlas
#

and it does make MUCH more sense that "setting velocity" is way better than just "teleporting" to maintain physics alright

leaden ice
#

deciding which velocity to set to

#

which you can do yourself too

small trench
crimson atlas
#

and solved my second problem which was this ugly conversion of "transform.up" into "new Vector2(transform.up.x, transform.up.y)" to correct some "amibuity" error VS popped up in some Vector2 vs Vector3 stuff

#

seems velocity will accept both?

leaden ice
#

both V2 + V2 and V3 + V3 are valid

#

and it doesn't know if you want to convert the V2 to a V3 or vice versa

#

since both are valid

#

ultimately it doesn't matter but the compiler needs to just be told which

crimson atlas
#

so it's an "error" i could've just ignored?

leaden ice
#

no you can't ignore it

#

but you can solve it in many ways that are all equally valid

crimson atlas
leaden ice
#

e.g.

rb.MovePosition(rb.position + (Vector2)transform.up);

rb.MovePosition((Vector3)rb.position + transform.up);``` would both work
crimson atlas
#

AHH i spent like 30 minutes trying <>, (), [], "as" lmao
didn't realize it goes before the variable

leaden ice
#

as would work too but is kinda sketchy here lol

#

rb.MovePosition(rb.position + (transform.up as Vector2));

#

although idk if that would get angry about nullables or something here

final aspen
#

https://hatebin.com/oigdrmybhr | https://hatebin.com/igfkydeuet i made these two scripts with help from youtube (thats why i want to make a drawer but its with the "doorOpen" or "doorClose" name) to make a drawer that open and closes i dooed the animations of it opening and closing and i maded this 2 scripts but its now working when i aim in the drawer my crosshair dont turn red and i cant press mouse0 to open it, pls help

heady iris
#

don't crosspost.

final aspen
#

i deleted other posts

#

i posted it here why i think this is not a beginners case

crimson atlas
#

now i wonder if there's some rigidbody.rotationVelocity i'm not aware of lol

heady iris
#

angular velocity

#

it's a float in 2D

crimson atlas
#

it's like i'm being introduced by a whole new world

leaden ice
#

loooking at docs == big brain

leaden ice
crimson atlas
#

lol

#

can i just set it like i set "velocity" won't it break anything?

heady iris
#

well, it's different from velocity...

leaden ice
#

it will make your thing spin

#

if you count spinning as breaking things

heady iris
#

it's a good trick

leaden ice
#

(or not spin, you know, depending)

heady iris
crimson atlas
#

oh yeah i just want to replace my rigidbody.rotation with this new guy

leaden ice
#

good idea

crimson atlas
#

dude i already feel like a pro coder

heady iris
#

position : velocity :: rotation : angularVelocity

#

scale : ?

#

actually, that's a good indication that scale is "weird" compared to the other two fundamental properties

crimson atlas
#

i'm even using overloads to avoid having to come up with weird names that would probably confuse me
Turn(CallBack context) subscribes to an input event and calls a local Turn(no arg) to make stuff happen

heady iris
#

i just read values directly from actions if I need them every frame

#

InputActionReference is lovely

crimson atlas
#

i explained that wrong though

#

i have a Turn(context) which just assigns values to a local var (just so i don't need to do that every single fixedupdate)

#

and another Turn (that is necessarily executed every fixedupdate) that grabs value from the local var

#

i guess all i did was take a check out of fixedupdate and have it happen only when value changes (inputaction event)

#

not a big deal i guess but personal progress

#

is it OK to link chatGPT "conversations" (the new feature they put out)?

#

in the subject of unity coding obvisouly

sleek bough
heady iris
#

i would rather not be exposed to the spam machine

crimson atlas
#

it does get things wrong though lol
for example it also thinks (probably because of the variable names) that "collider" refers to ourselves and "otherCollider" to the 'other guy', however it's the other way around

heady iris
#

yes, because it's a large language model

#

it produces text that is likely to follow the prompt

#

ask it how to set the static friction of a 2D physics material

#

it will probably explain how to do that, even though 2D physics materials do not have static friction

#

(i would be impressed if it actually correctly responded that there is only friction)

crimson atlas
#

it is, and it probably uses its training with the unity docs to answer that kind of stuff
and from reading unity docs you really think "otherCollider" is the other guy.
only through you experience you learn it's the other way around

heady iris
#

well, no, you read the docs and they say what the variables mean

crimson atlas
heady iris
#

collider:

The incoming Collider2D involved in the collision with the otherCollider.

#

otherCollider:

The other Collider2D involved in the collision with the collider.

crimson atlas
#

all the docs say to differentiate between them (besides referring to one as "collider" and the other as "other collider" is to say "collider" is the incoming one)
isn't incoming the guy which is moving?

heady iris
#

it's the one that is coming in and hitting us

#

i agree that otherCollider should have been named ownCollider or something

crimson atlas
#

exactly

#

to name something "otherCollider" while it's giving information about "myself" (the script's object) is like making an effort for people to confuse it

#

the other problem with the word "incoming" is
if A (script) is moving and hits B

B is the "incoming" guy (despite it being a static object)

#

is it the same with Collider (3D)?

#

at least it's described much more directly (and unambiguously)

simple egret
#

Oh hey, still on this? Yeah 3D is much more explicit on this even for contact points, thisCollider, otherCollider

royal pulsar
#
private Vector2 CreateRandomDestination()
    {
        Vector2 currentPosition = transform.position;
        float newX = Random.Range(-maxDistance, maxDistance);
        float newY = Random.Range(-maxDistance, maxDistance);
        Vector2 destination = new Vector2(newX, newY) + currentPosition;

        while (DestinationBlocked(currentPosition, destination))
        {
            newX = Random.Range(-maxDistance, maxDistance);
            newY = Random.Range(-maxDistance, maxDistance);
            destination = new Vector2(newX, newY) + currentPosition;
        }

        return destination;
private Vector2 CreateRandomDestination()
    {
        Vector2 currentPosition = transform.position;
        float newX = Random.Range(-maxDistance, maxDistance);
        float newY = Random.Range(-maxDistance, maxDistance);
        Vector2 destination = new Vector2(newX, newY) + currentPosition;

        if (DestinationBlocked(currentPosition, destination))
        {
            return new CreateRandomDestination();
        }

        return destination;

is one of these solutions preferred over the other?

#

i guess the recursion is doing the same thing

heady iris
#

recursion could eventually cause a stack overflow if it goes on for a long time

knotty sun
royal pulsar
#

Oh yeah

#

So maybe a counter and after x tries it stops searching?

knotty sun
#

yes, also set a bool to know that it has 'timed out'

gray mural
#

does anyone know how words in TMP_Text are transferred to a new line?

#

perhaps "where?"

#

or in TextMeshProUGUI..

#

I guess in GenerateTextMesh()

crimson atlas
#

so when making a list of gameobjects that compose the player (snake segments in my case)
i see people using a list of "Transforms"
why not "GameObjects" or even "Rigidbodies" instead?

gray mural
simple egret
#

It goes down to what is accessed a lot when using a list item. If you store GameObject but access their position, you'll have to do .transform.position every time

gray mural
#

and it sounds more logical to use Transform, not GameObect or Rigidbody

crimson atlas
neat echo
gray mural
#

unless you don't need its Transform

rocky laurel
#

Is it possible to make a scene reload if a certain error pops up in the console? Let me know.

vernal plank
#

Texture propte = material.GetTexture("_MainTex"); this is doing what expected
material.SetTexture("_MainTex", extexture); this is not assighing the texture

#

w h y

#

Material material = AssetDatabase.LoadAssetAtPath(materialPath, typeof(Material)) as Material;

#

do i need render component

#

Am trying to change material texture with editor script

#

the material has a graph shader

#

but i dont wanna change the graph shader

#

i wanna change the material instance (its a normal mat)

vernal plank
crimson atlas
#

is a static class adequate for implementation of a game manager (unique) class?

vernal plank
#
public class AssetDatabaseExamplesTest : MonoBehaviour
{
    [MenuItem("AssetDatabase/printmat")]
    static void SubFolderExample()
    {
        var folders = AssetDatabase.GetSubFolders("Assets/Silex-Materials_Pack/Textures");
        string foldvar = folders[3];
        string[] files =  Directory.GetFiles(foldvar+"/", "*.png", SearchOption.TopDirectoryOnly);
        string wellyay = files[0];

        string materialPath = "Assets/Silex-Materials_Pack/Materials/test/Mat_test.mat";

        Texture extexture = (Texture)AssetDatabase.LoadAssetAtPath(wellyay, typeof(Texture));
        // Texture2D extexture = (Texture2D)AssetDatabase.LoadAssetAtPath(wellyay, typeof(Texture2D));

        Material material = AssetDatabase.LoadAssetAtPath(materialPath, typeof(Material)) as Material;
        // Debug.Log(material);
        material.SetTexture("_MainTex", extexture);
        Debug.Log("well",extexture);
#

its editor script

#

its public class i guess

#

am trying to change the texture of a material

#

without effecting its shader

potent sleet
rocky laurel
#

how do i fix this? Bonzi is going forward, like he should, but Peedy seems to sink. They both use the same AI wander script.

simple egret
urban berry
#

I'm running into this really weird issue all of a sudden where Unity keeps tagging some of its own built-in components as not recognizable as monobehaviours

#

so prefabs lose their links to these scripts
It was happening to NetworkTransport before, and now it's happening to NetworkObjects
If I go into the prefab and reassign the script it "works" but as soon as I exit the prefab and it saves it, it loses the link on the prefab again and shows up as a missing script

rocky laurel
simple egret
#

The blue arrow (you're in rotation mode, switch back to move mode) points down

#

Probably

rocky laurel
#

is it pointing down

simple egret
#

Well use your eyes, definitely not

rocky laurel
#

lol

#

whats the issue then

#

this ones working, and its the same

simple egret
#

It points backwards though, but it might be a setup issue

pliant locust
#

does anyone here really good at coding C3 scripts?

#

c#

urban berry
# rocky laurel

The blue vector is the Z forward vector and should be pointing forwards, not back

pliant locust
#

anyone?

simple egret
#

Make sure your Move tool is in Pivot Local mode first. These are two buttons above the scene view

tacit portal
#

yoho friendly ppl

void OnTriggerEnter2D(Collider2D col)
    {
        if(col.CompareTag("Player"))
        {
            maxHP--;
            ShowFloatingText();
            if(maxHP == 0)
            {
                gameObject.SetActive(false);
            }
            
        }
    }

    void ShowFloatingText()
    {
        Instantiate(popUp, transform.position, Quaternion.identity, transform);
        Debug.Log(maxHP);
    }

the pop up text isnt showing for some reason. When i debug, then the hp is properly reduced with each hit, but only after it reached 0, does the pop up GO get instatiated, according to the hierarchy

simple egret
simple egret
urban berry
crimson atlas
#

do i necessarily have to attach my "GameManager" script to a GameObject in order for it to execute its awake, start, update etc functions?

simple egret
#

Well the blue axis is up now

urban berry
simple egret
#

Meaning your AI wandering system actually pushes objects along the backward direction

rocky laurel
simple egret
#

These were probably exported from Blender, but as Blender is Z-up, it's broken

rocky laurel
#

oh

#

right

simple egret
#

You'll have to export again, with the correct axis settings

simple egret
urban berry
#

I'm gonna try this before doing the downgrade since it's a lower hanging fruit

rocky laurel
simple egret
#

I have very limited blender experience

#

!blender

tawny elkBOT
simple egret
#

Ask there

urban berry
#

blender uses a Z up

#

Unity uses a Y up

#

I think you can fix the problem with your export settings

simple egret
#

Yeah I remember seeing that, eh just try random combinations until it works

#

There's a 1/27 chance of getting it right the first time, good luck!

potent sleet
#

this isn't one

cobalt gyro
#

if variables are private by default then whats the purpose of using the private keyword

simple egret
#

Being explicit about it

urban berry
#

but here's something for @rocky laurel before you go to the modelling help department. This is in the export options. Muck with those.

simple egret
# simple egret Being explicit about it

Did you know that classes and other types that are not marked with an access modifier such as private, are internal by default? So it's not always private, better be explicit about it!

rocky laurel
#

all working. thanks so much for your help!

simple egret
urban berry
#

but, by default, public variables are SERIALIZED (meaning they show up in the inspector and these values are STORED in scene data or asset data

pliant locust
#

can i actually get help

urban berry
#

But you can add [SerializeField] to force this same behaviour upon any non-public members
and it will only work upon serializable data types

pliant locust
#

cuz im following the tutorial step by step and this one part isn't working

urban berry
pliant locust
#

i dont understand dont ask to ask

#

it makes no sence

urban berry
#

don't ask if it's okay if you can ask a question

#

just ask your question

#

state the problem, let's see how your tutorial is breaking

#

we'll git er dun

simple egret
#

It eliminates the "can I ask you guys something" preliminary question that just wasting some time

#

It optimizes the time and space here, and as programmers oh boy do we like optimization

pliant locust
#

so basically it says to add a gird layout group to my toolbar ui image, i can add it, but when i duplicate my inventory slot (like the tutorial says) i doesnt do anything, when it should be spreading them out

#

oh so basically saying, can i get help, instead you state your problem

urban berry
#

okay, we need a screenshot of the UI (that is broken) plus a shot of your hierarchy, plus a shot of your inspector

#

we'll move from there

pliant locust
#

can i just send one full screenshot?

urban berry
#

go for it

pliant locust
#

not full photo but that's all ya asked for so thereeee

#

lol

urban berry
#

nono that's fine

pliant locust
#

when i duplicate the inventoy slot it should be looking something like this

#

but when i do duplicate it it does nowthing

#

nothing8

#

nothing***

urban berry
#

so they all get centered?

pliant locust
#

yeah

#

but when i duplicate it nothing happens

urban berry
#

well, what DOES happen is all of the slot objects are being tiled atop each other

#

may we see an inspector screenshot of the inventoryslot object as well?