#💻┃code-beginner

1 messages · Page 245 of 1

wintry quarry
#

tf.Rotate(tf.position * movespeed * Time.fixedDeltaTime); << What on earth is this

autumn tusk
#

the crosshair is not a child and its still acting like this

wintry quarry
#

that line of code is nonsense

#

remove it

#

it's not going to do anything either since you're overwriting the rotation a few lines later with tf.rotation = Quaternion.Euler(0, 0, angle);

hidden sun
#

hi, can i somehow make a static vector3 get; set;? to save data for other scene???

wintry quarry
#

Make an actual class to hold the data

hidden sun
#

yeah, i have a class

#

in which i want to have a vector 3

wintry quarry
#

ok now keep a reference to that class in either a DDOL singleton or a ScriptableObject

hidden sun
#

what's the syntax?

wintry quarry
#

for what

hidden sun
#

umm... i think i forgot something

#

so..... i want to make a static vector3 in a static class and the vector will have 3 classes

wintry quarry
#

Bad idea

#

don't use static variables like that

#

Make an actual class

hidden sun
#

ugh i want to pass the pos of 3 obj to other scene

wintry quarry
#

and keep an instance of it referenced from a DDOL singleton or ScriptableObject

#

Yes I'm explaining the best way to do it

hidden sun
#
public static class Pdatas
{
    public static Pdata Plane1 { get; set; }
    public static Pdata Plane2 { get; set; }
    public static Pdata Plane3 { get; set; }
    public class Pdata
    {
        public int PosX { get; set; }
        public int PosY { get; set; }
        public int Rotation { get; set; }
    }
}
#

instead of p1 2 3 i want to make a vector

wintry quarry
#

What's stopping you?

#

You mean a list?

#

Use a list

#

Or array

hidden sun
#

it stupid because its easier with other method or?

wintry quarry
#

Because static variables are a bad idea for many reasons. it will be hard to manage this way

swift crag
#

static variables mean that you get one -- and only one -- instance of that data

hidden sun
#

single use

swift crag
#

it's also annoying to serialize and deserialize static data

wintry quarry
#

You will need to manage this completely manually

#

and yes serializing will be difficult too

hidden sun
#

um.. im not doing much with it, just single read in the next scene

wintry quarry
#

You want something like this:

public class GameData {
  public List<PData> Objects;
}

public class PData {
  public Vector2 Position { get; set; }
  public int Rotation { get; set; }
}```
hidden sun
#

yes

wintry quarry
#

then you can keep an instance of GameData on a singleton or a ScirptableObject

swift crag
#

Once you have the GameData, I think it would be fine to just stuff it in a static field to get it from Scene A to Scene B. You can build something more complex if you need it later.

wintry quarry
#

anyway I don't see what the issue you were having was. Are you confused about the difference between a Vector and a List?

autumn tusk
#

setting my camera refresh rate to fixedupdate fixed this

hidden sun
#

i didnt get the syntax

#

ithink

#

solved, thank you

buoyant rune
#

can somebody help me, the enmy dies but it stands back up no clue why, the death animation isnt looped

rich adder
#

have you disabled its colliders on death?

#

nvm was looking at wrong clip

buoyant rune
thorn iron
#

How can I get an image of a 3D GameObject, the background must be transparent ? (I can choose the camera angle to take the 2D image)

rich adder
#

you probably need to disable transition to self

buoyant rune
#

was off already

rich adder
thorn iron
#

will it take the background?

#

or I can make it transparent

rich adder
#

it will give you transparent background or you can set one up

median ruin
#

What does it mean to make a variable static?

rich bluff
buoyant rune
rich bluff
#

all classes have static and non static part, static exists as a single instance, available through the class name

grizzled zealot
#

I have a dynamic RB (parent) and a kinematic RB (child). Both have and need a collider. If I addforce to the dynamic RB, it's still sometimes colliding with the kinematic RB, although the kinematic is a child. Are they not moved together?

rich bluff
#

by marking field or method as static you put it into the static part

rich adder
median ruin
rich adder
#

only one can exist yes

rich bluff
#

in a sense yes, only 1 static class exists globally, it is created for you by the .net and you cant delete it

rich adder
#

in the context of unity also you will not be able to set / see it in the inspector

median ruin
#

hmm okay

rich bluff
#

so if a variable is public and static, anything can access and change that value

grizzled zealot
rich adder
rich bluff
#

class Foo
{
   public static int count;
   public int nonStaticCount;
}

void Test()
{
  Foo.count = 5;
  Foo foo1 = new Foo();
  foo1.nonStaticCount = 1;
  Foo foo2 = new Foo();
  foo2.nonStaticCount = 2;
  Foo foo3 = new Foo();
  foo3.nonStaticCount = 3;

  // Foo.count is 5, the rest have unique values
}
grizzled zealot
rich adder
median ruin
# rich bluff so if a variable is public and static, anything can access and change that value

Hmm.. I want to generate a getter and a setter but also be able to set the value in the editor, but the issue is that it doesn't appear in the inspector. I tried making a secondary value that is accessible in the editor that gets applied to the getter/setter
like this

[SerializeField] float _decay = 1.0f; 
public float Decay { get; set;} = _decay;

But unfortunately this is wrong.

grizzled zealot
rich adder
median ruin
#

does the set need to be private?

rich bluff
median ruin
rich adder
rich bluff
#
[SerializeField] float _decay = 1.0f; 
public static float Decay {
    get => _decay;
    set => _decay = value;
}
#

this is a hack by the way

median ruin
rich bluff
#

i dont recommend as a wide use pattern

humble island
#

how to properly duplicate an object?

rich bluff
#

problem with your initial example is that the value is only assigned at the object creation

buoyant rune
rich adder
rich bluff
#

or its not assigned at all, most likely its a compile error

buoyant rune
median ruin
humble island
rich adder
rich bluff
#

im becoming confused, you want to use static there or not?

rich adder
median ruin
#

Well I want to be able to change it in the editor and in game, but I have heard that it is bad to use public on variables?

rich adder
#

depending on gameobject names is a horrible idea

#

and goes against the whole type-safety concept anyway

rich bluff
#

its a blanket advice that if not explained why, will lead you towards bunch of wrong assumptions

humble island
rich bluff
#

in short you by default strive to keep everything private, and resort to using public on things that are intended to be modified externally

median ruin
#

I see

rich adder
median ruin
#

Well this value is intended to be changed

rich bluff
#

the assumption is - if its public it is an indicator of intent to be used and changed

humble island
median ruin
rich bluff
#

its not wrong or bad, its just a way to interact with APIs, that has to be designed carefully

rich adder
humble island
#

putting the cloned object on specific position

rich adder
swift crag
#

Being public or private is different from being serialized or non-serialized

median ruin
humble island
buoyant rune
swift crag
#

Okay, so you have to either make the member public or provide a way to modify the member that's public.

#

The latter lets you control exactly how the field is changed.

swift crag
#
public void SetAngle(float newAngle) {
  angle = Mathf.Repeat(newAngle, 360);
}
#

for example

humble island
swift crag
#

make a thread.

rich adder
buoyant rune
median ruin
rich adder
queen adder
#

replaced the green with my own version below, cringe or nah?

rich adder
buoyant rune
humble island
#

Proper way of cloning gameobjects

rich adder
buoyant rune
rich adder
#

are you getting error or what

buoyant rune
#

no error juts a bug

#

the enemy dies , yet still patrols

#

after

#

i'll show u with a gif

queen adder
rich adder
buoyant rune
#

could u double check i aint too sure

rich adder
#

you def have console error at runtime

#

patrolBehaviour and boxCollider are not assigned anywhere

buoyant rune
rich adder
buoyant rune
#

theres this , but this is from ages ago doesnt affect enemy death

#

apart from that nothing else

#

this isnt the issue tho

buoyant rune
rich adder
#

this is when enemy died?

buoyant rune
#

yep

rich adder
#

I need to test, somehow Destroy doesnt throw null I guess.

#

Okay either way, you havent assigned them

#

so it has no idea what to destroy

buoyant rune
#

where do i assign it

rich adder
#

the same way you assign stuff in PatrolBehaviour

#

[SerializeField] private then use the Inspector

buoyant rune
#

oh oh

#

and do that in the enemy health script?

rich adder
#
 if (EnemyIdleTimer > EnemyIdleDuration)
            moveLeft = !moveLeft; // only this line belongs to if statement check
        EnemyIdleTimer += Time.deltaTime;

Btw when you Dont use brackets only the first line is part of the If statement block

buoyant rune
#

now that it destroys it does this

#

also

#

in my game im going to have multiple enemies, doesnt me destroying the script for patrol affect all other enemies

rich adder
rich adder
#

other enemies should not be affected from this single instance

#

Is PatrolBehavior on the Enemy ?

buoyant rune
#

yes

#

i just tested something and duplicated an enemy and when i kill one, the other one complelety freezes

#

possibly because the patrolbehaviour destroys

rich adder
#

unless you made something flawed or global

buoyant rune
#

i have one enemy type tho

swift crag
#

is PatrolBehaviour on a completely separate prefab?

buoyant rune
#

wait

#

mnightve found the issue

#

should the patrol behaviour scriptbe assigned to the prefab enemy?

rich adder
#

no

#

it should be inside the prefab then inside the prefab you assign everything

swift crag
#

if every enemy instance shares a reference to the same patrol behaviour, then destroying it will, unsurprisingly, leave every enemy without a patrol behaviour

buoyant rune
swift crag
#

no, it should be in the enemy prefab.

#

When you instantiate a prefab, any references within the prefab will point to the corresponding object in the instance

#

Your enemy prefab should look like this:

#
  • PatrolBehaviour
  • EnemyHealth
  • BoxCollider2D
#

all of those components should be on the prefab, and you should assign references to them within the prefab

buoyant rune
#

this is my prefab

median ruin
#

Is there a way to get the amount passed since start? or creation of the instance of a script?

swift crag
# buoyant rune

That looks fine. Each enemy will have their own patrol behaviour

median ruin
#

I'll try it

rich adder
#

^ this also you can record each spawn with DateTime.Now and compare time too

rich adder
median ruin
#

What is a record?

buoyant rune
rich adder
buoyant rune
rich adder
#

just blank?

median ruin
buoyant rune
#

yep

median ruin
#

thanks

quick pollen
rich adder
swift crag
# buoyant rune yep

Destroying one enemy's PatrolBehaviour will do absolutely nothing to any other enemy's PatrolBehaviour

rich adder
frigid sequoia
#

So is this how you are supposed to use the SmoothDamp? Cause I didn't find an example outside the Update method

primal turtle
#

does OnMouseOver just not work for tilemap?

swift crag
wintry quarry
rich adder
swift crag
#

So, yes, that looks fine

primal turtle
primal turtle
#

oh hi navarone!

buoyant rune
rich adder
primal turtle
rich adder
primal turtle
#

does the orthographic view change anything?

rich adder
#

nah i think the issue is tilemap coordinates are not the same as world coordinates

swift crag
#

isn't the tilemap collider one big collider?

rich adder
#

also that

#

it shrinks/expands depending ontiles

primal turtle
rich adder
#

make your own ray then use tilemap.WorldToCell

primal turtle
#

but it won't send anything, debug doesn't even run, which means the funtion isn't being called.

primal turtle
rich adder
median ruin
#

Why should I use record in this instance? am I not just storing a value in a variable?

median ruin
#

What?

swift crag
#

"Record" as in the verb

#

record the current value

#

i missed that

rich adder
#

Yeah I meant that lol

median ruin
#

oh-

#

Lol

rich adder
# primal turtle any good tutorials?
   var worldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            worldPos.z = 0;
            var cellPos = yourTilemap.WorldToCell(worldPos);
            if (yourTilemap.HasTile(cellPos)) return;
                //do something with tile here```
frigid sequoia
primal turtle
#

thx so much!!

frigid sequoia
#

I don't quite get it

swift crag
primal turtle
swift crag
#

It returns the new position. It also updates the current velocity, which is passed by reference with the ref keyword.

#

You just have to call the method repeatedly

rich adder
primal turtle
#

ok

rich adder
#

@primal turtle what are you trying to do exactly , maybe there is something else

swift crag
#

SmoothDamp has a deltaTime argument that defaults to Time.deltaTime, so you don't have to explicitly tell it how much time has passed if you're running it every frame.

gilded verge
#

hey its been sometime since i used unity i cant seem to find the navmesh window nor can i find the agent component...

primal turtle
#

just trying to know whether the mouse is on the tilemap as a whole or not

primal turtle
#

this was supposed to be simple...

rich adder
#

yeah tilemap.HasTile does that

frigid sequoia
swift crag
wintry quarry
swift crag
#

the fourth argument is how long it should take to reach the target

#

This isn't a Lerp method.

#

You aren't telling it how far along you are.

gilded verge
swift crag
#

All you do is tell it:

  • Where you are
  • Where you want to be
  • What your velocity is
  • How long you want it to take
primal turtle
#

can I specify what tile I want it to search for using .Hastile?

#

wait nvm

rich adder
swift crag
rich adder
#

so you can make your own tile

frigid sequoia
gilded verge
swift crag
#

I guess it technically does if you call it every frame

#

But it doesn't magically "know" how long it's been

rich adder
frigid sequoia
#

That's what I was referring... so it just take starting point, end point and calculates based on the acceleration and the deltaTime where should it be, isn't it?

rich adder
#

not really code related

fringe plover
#

Damn wrong channel sry, ill repost

swift crag
wintry quarry
swift crag
#

That lets it remember how fast it's going from call to call.

wintry quarry
#

Or use DotTween which handles the whole thing for you

frigid sequoia
swift crag
#

"reset to the ref"?

frigid sequoia
#

Like, it remembers the acceleration it had in the last call; how do I tell it "nah, forget about that, we are doing a new transition"?

swift crag
#

by using a different velocity variable

#

Nothing is stored in SmoothDamp at all. There is no static data here.

#
public class ExampleClass : MonoBehaviour
{
    public Transform target;
    public float smoothTime = 0.3F;
    private Vector3 velocity = Vector3.zero;

    void Update()
    {
        // Define a target position above and behind the target transform
        Vector3 targetPosition = target.TransformPoint(new Vector3(0, 5, -10));

        // Smoothly move the camera towards that target position
        transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime);
    }
}
#

if I wanted to use SmoothDamp for two unrelated things, I'd need two velocity variables

#

There is no magic. It doesn't run by itself, or remember values from call to call, or anything like that

#

Given a position, destination, velocity, and smoothing time, it gives you a new position and updates the velocity.

#

That's it.

frigid sequoia
#

I mean, if I call the Coroutine again, I am guessing the acceleration value is considered "new" and the ref is not stored from the last call

swift crag
#

so, yes, the two enumerators produced by calling energyCounterTransition twice will have two different variables

#

If transitionVelocity was a field on the class you defined energyCounterTransition in, then two or more coroutines would wind up fighting over it.

vale karma
#

hey guys, so i ran into a pretty big flaw in design, I have a movement state machine hierarchy, and the problem is the substates (idle, walk, run) ExitStates are not getting called when changing out of the parent grounded state. Is there a way i can ensure ExitState gets called 100% of the time?

rich adder
vale karma
#

Ill send code in a sec

#

But if you look close at the bool checks at the bottom, if i am walking and jump (leaves grounded state) the walking anim never gets called to turn off

#

But if i walk and then run it works bc i never leave grounded state

rich adder
#

yeah the bools are runining the whole point of being in a single state

#

you need a cleaner way to activate the states

vale karma
#

Yeah i knew i set it up in a bad way, i just cant find good documentation to follow

#

I just activate the animation on the EnterState, and disable it on exitstate

#

And trigger for jump

rich adder
#

you're not using the built in scripts states right?

vale karma
#

Uh, i think i am, i dont understand how to animator and state machine are supposed to work together, or if they do the same thing

#

I am using my script/state machine for the bool values

#

Are you saying i could just play the animation directly through code?

rich adder
vale karma
#

Oh thank god

queen adder
#

There's a custom class for animation states as well

vale karma
#

Oh god no

rich adder
#

yeah the build in script states

queen adder
#

It's not bad

#

It's pretty good imo

vale karma
#

Please, no, not another wall😂

queen adder
#

It's still c#

vale karma
#

Ill check it out, i gotta get a faster workflow im moving at a snail’s pace😂

#

I attempted setting up github all yesturday and it didnt even work

rich adder
#

there are plenty of tutorials on that system

queen adder
#

It just gives you access to the animators call backs / events.

vale karma
#

i read thru it, im lookin up statemachine behavior, is that specific enough?

gilded verge
#

is it okay if i use the obselete navmesh? i cant see the bake navmesh in the new one..

rich adder
fringe swallow
#

Hello guys (sorry if me english is bad), I want to make a weapon can bounce on nearby enemies, but I don't know how I can get the distance of the all enemies that exist in the camera so that is bounce. ¿How can i get the distance of the all enemies in the camera or scene? 😭

rich adder
#

Vector3.Distance would work

#

if you mean in the view only probably do a overlap then calculate dot product to each one to see if its within a range "infront", or just use a boxcast forward

wind raptor
#

Is there a way to have a Serialized field which can accept one of two types of objects?

#

Without having a serialized reference to a common parent class and verifying in Start or something

eternal needle
eternal needle
wind raptor
queen adder
#

Interfaces as well

eternal needle
#

It is possible in other ways but tedious to do with interfaces because you cannot drag in inspector by default

queen adder
#

Oh you cant?

eternal needle
#

You would need custom inspector stuff for any other solution

rich bluff
queen adder
#

My apologies then

gilded verge
cosmic mural
#

what does this error mean?

rich adder
gilded verge
rich adder
rich bluff
rich adder
#

it has many filtering methods too like if you want only certain layers etc. @gilded verge

gilded verge
rich adder
#

i suggest you lookup the documentation on it

wind raptor
eternal needle
gilded verge
rich adder
fringe swallow
rich adder
queen adder
#

Sr.x?

fringe swallow
#

Hello

queen adder
#

Im confused by what ur saying

rich adder
#

that will check all enemies within a zone

#

then do a loop to each one for the bullet path or w/e ur doing

rich adder
fringe swallow
fringe swallow
gilded verge
rich adder
fringe swallow
#

But, the enemies have a distance in the map, the weapon have a distance to, but I don't know how to access the distance of the enemy with respect to the weapon or the bullet because they are different objects

quick summit
#

hello, I have seen a lot of tutorial, but they don't seem to work. Do anyone know what version I should use?

rich adder
#

to find all those objects with a range, once you do you do a loop to find the distance for example

fringe swallow
#

Aaaaaah!!!! 🤯

#

Im gonna try something, THANKS!! UnityChanClever

eternal needle
rich adder
quick summit
rich adder
#

unless ur looking at some js-like syntax which is very old

eternal needle
summer stump
static bay
#

Actually you know what

summer stump
static bay
#

This is a damn good flow chart

quick summit
summer stump
quick summit
#

yes

summer stump
#

Maybe you need to download it? It's full resolution but discord sometimes compresses images

quick summit
#

ok

faint sluice
#

That's so beautiful i can look at it for hours

hidden sun
#

how do i unsubscribe from player events?

#

callbacks?

rich adder
#

-=

hidden sun
#

umm all?

rich adder
#

well unityevent and c# are different thats why im tasking

hidden sun
#

im subscribing in a scene to send/receive some messages

rich adder
#

then its RemoveListener

#

i usually put it in OnDisable

cinder mason
#

my movement script works fine but when i try and walk into a wall it starts glitching in and becoming jittery

    private void Update()
    {
        direction = movement.action.ReadValue<Vector2>();
        float sprinting = sprint.action.ReadValue<float>();
        float currentSpeed = speed;

        //changes which speed to use if player is sprinting
        if (sprinting > 0)
        {
            currentSpeed = sprintSpeed;
        }
        else if (sprinting == 0)
        {
            currentSpeed = speed;
        }

        if (canMove)
            GetComponent<Rigidbody>().MovePosition(GetComponent<Rigidbody>().position + new Vector3(direction.x * (currentSpeed * Time.deltaTime), 0, direction.y * (currentSpeed * Time.deltaTime)));
    }
wintry quarry
#

It belongs in FixedUpdate

#

Move via velocity

#

MovePosition will happily move you inside a wall

cinder mason
#

so this?
rb.velocity = new Vector3(direction.x, 0, direction.y) * (currentSpeed * Time.deltaTime);

#

(in fixed update)

wintry quarry
#

Do not multiply DeltaTime

#

Otherwise yes

#

Velocity is already adjusted to be per second

cinder mason
#

you mean use fixedDeltaTime?

wintry quarry
#

No

#

Use neither

summer stump
cinder mason
#

ohh ok

crisp copper
#

what is this error mean?

wintry quarry
crisp copper
#

!code

eternal falconBOT
crisp copper
#

what is wronge in that script so i get that error?

vale karma
#

you guys shouldnt have told me about a better way to do animations, i went from "i need some functionality and animation" to "ooo procedural animationnnnnssssss"

north kiln
crisp copper
#

i dont know ether i followd a tutorial and got that error

rich adder
north kiln
#

Also, by sending a screenshot of the console window and not the error underlined in your IDE, it indicates that it's likely unconfigured. !ide

eternal falconBOT
rich adder
crisp copper
cinder mason
uncut shard
#

I am facing this problem
it is shaking in bottom

rich adder
paper star
#

can someone help me with this code?
i have the problem that i wanna split up the code of the X and Y axis because the gravity pulls my character and moves it across the map

vale karma
#

im not finding the right way to implement animations into my state machine script... theres the blend tree and transitions with booleans, is there any other way?

paper star
#
using System.Collections.Generic;
using UnityEngine;

public class MouseY : MonoBehaviour
{
        public float mouseSensitivity = 500f;
        float yRotation = 0f;
    
    void Start()
    {
      Cursor.lockState = CursorLockMode.Locked;

    }

    // Update is called once per frame
    void Update()
    {
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity;
        
        xRotation = Mathf.Clamp(xRotation, -89f, 89f);
        Rigidbody.localRotation = Quaternion.Euler(xRotation, 0f);
    }
}
wintry quarry
shadow vigil
#

I was wondering if anyone has any good recommendations on a tutorial series for how to set up a 2D inventory system? been trying to set it up for a while but been struggling

rich adder
#

every inventory is different and people use many different ways to do it

#

instead of following a series, recommend you just learn what parts you will need and go from there

timber tide
#

Yeah, they can be either super simple or complex af

rich adder
#

yup start with a basic one list / dictionary

#

learn how to use a dictionary you'll make one quick

timber tide
#

Ideally, don't have a resizable inventory, craft your inventory prefab beforehand and serialize the exact UI slots to the script on the editor.

shadow vigil
#

okay thanks for the advice 🙂

eternal needle
vale karma
#

i just completed a really in depth tutorial series on an inventory system, it took me a week or so of hours a day

eternal needle
#

If the user doesnt need to do much then it can be extremely simple

timber tide
#

im remaking mine right now to make it less complex

vale karma
#

this one is perfect, equipable objects, swapping, deleting yada yada. but it falls into "you need this for this to work" kind of thing. along the lines of what theyre saying

static bay
vale karma
#

hehehe

timber tide
#

having different inventory types like equipment slots also adds some complexity since you're now making sure you can swap items into it

#

because inventory can have all item types, but each equipment slot can only have a single type

#

and if you've got drag/touch controls then you need to duplicate a lot of that logic

#

then you have your hotbar which you may want to store equipment on too so you can quick swap, but then you need to make exceptions for that too

rich adder
timber tide
#

oh no

vale karma
#

im not finding much on coding animation instead of using booleans or blend trees

rich adder
vale karma
#

huh

#

like two nodes being true at the same time?

#

so i could take the ground bool out?

rich adder
#

2 bools of state both true = you're not in a finite state lol

vale karma
#

shit nvmd, i got some learning to do

rich adder
#

What you could potentially do is use Enum cast to int then use that to activate a state

#

so instead of bools use int coming from state

vale karma
#

couldnt i just check if its in a state or not? that may be easier but it just made my perspective more confused haha

#

the flaw with what i have rn is its not calling exitstate from each substate method once it changes superstates

rich adder
vale karma
#

its not necesarilly leaving the substate, its more like turning it off or pausing it

#

and switching super states, and so the bool always stays checked until i enter the state again, then it fixes itself

rich adder
#

thats why i dont think its good to have bools instead its more assured to use an int

vale karma
#

so if i walk and then jump ill still be walking when i land but not move

rich adder
#

bools can be in multiple states

#

int cannot

vale karma
#

okay, im not sure how to go about creating that

rich adder
#

is your statemachine in code an enum ?

vale karma
#

no

rich adder
#

oh..

vale karma
#

yea, its hard to tell what to do. theres too many ways to do the same thing

#

i wish there was a vc channel, problems would be so much easier to talk about

rich adder
#

something like cs public enum States { Idle, Walking, Sleeping } public States statecurrent; void ChangeState(States state) { statecurrent = state; anim.SetInteger("state", (int)statecurrent); }

vale karma
#

yea, i guess this one is supposed to be much more robust and modular or something idk

#

trying to make a game that is as clean and dry as i can get it. i figure if this is easier for more exp devs that me taking a really long time not rushing to finish at each step would soon get good results

rich adder
#

I just use the most straight forward way until i need to expand, otherwise if i sit there thinking of every little Design aspect Ill never accomplish anything

#

my earlier projects were over-designed / overengineered when sometimes the KISS method works best

vale karma
#

i did that, but took note of what made it harder for me to continue, those things were movement capabilities, inventory system, saving, and procedural environment

#

now im trying to make sure or gauge how good i need these to be before i keep goin

rich adder
#

those can get complex fast

vale karma
#

ohhhh yea

#

i want to stick with just walk run jump, but theres also falling, which i am having a real hard time implementing

rich adder
vale karma
#

how would i fall, only if the jump animation completed, im not on the ground, and its not gonna look funky if it hits .1 seconds or somethign of animation

rich adder
#

statemachine is a concept not a particular way to do it

#

as long as you exist in a single state, you have a state machine

vale karma
#

wha..buh.. ujwah

#

*windows xp restart

#

*windows xp loading

#

*windows xp loggin

#

would the enum and animations affect my movement scripts?

rich adder
#

why would it

north kiln
#

Why do you do hit.collider.gameObject == gameObject

#

also, I doubt you want a raycast, and instead want an OverlapPoint

vale karma
#

i dont know, somehow my animations became physical and started bullying my movement

rich adder
vale karma
#

yea i went thru that dumpster fire, fixed that, but i still have the fundemental issue that my substate code doesnt complete if i exit the superstate

summer stump
#

Why would an object want to hit itself?

north kiln
#

Oh, every script that wants to be clicked does it's own raycast? Yuck

#

You should only raycast once from the camera and check if what was hit is clickable

rich adder
#

why do you have substates already if you only had those 4 states or w/e

vale karma
#

because later on, when i add attacks, death, swimming, flying if theres a need, transportation and even load screens, that enum list will get extra long

rich adder
#

the what ifs i was talking about earlier

#

also those mentioned wouldn't need to be substates anyway

vale karma
#

yeah but i got stuck once i wanted to add more than just jump, move, crouch, and sprint

rich adder
#

your flying and swimming controls would probably not be the same would they

north kiln
#

I have no idea. As I said, I would use OverlapPoint. And actually do some debugging beyond a single log

vale karma
#

no not at all lol, but you wouldnt want to be able to attack an enemy if your dead, you dhave to check for that, or if you could use a power move only when your hurt and about to die, etc, theres alot i could do with it

#

im not doing it justice trying to explain it well but it has its benefits

rich adder
#

unless you had some revive potion or respawning

vale karma
#

like rn i can use it so when im in the air, or falling, i cant move the character

summer stump
#

They weren't talking to you I think

vale karma
#

it would be a bit different to code, maybe a bit more destructive than just not including it in what the player is allowed to do in that state

#

its only flaw is the user in this case is not smart enough to use it well XD

rich adder
#

imo is better to start simple and add on from there complexity as you go than to start complex with so many options that you might not even need

vale karma
#

i learned that the hard way with graphics sadok

frigid sequoia
#

Why the heck is my value going down? Isn't this supposed to go from first value to second value?

vale karma
#

i know it has to do with the order that the switchstate is called, i think exitstate(); may be in the wrong place?

dusty silo
#

I am getting the error: 'ArgumentNullException: Value cannot be null.'
Relevant code segments:

//from a class of static functions
#nullable enable
    public static Edge? getEdgeFromPoints(Vertex a, Vertex b) {
        List<Edge> intermediate = a.connectedEdges.Intersect(b.connectedEdges).ToList(); // error here ^, making this list nullable does not help
        return (intermediate.Count < 1 ? null : intermediate[0]);
    }
// from my Polygon class
 private void pointsToEdges() {
        if (_borders == null) _borders = new Edge[_points.Count];
        Edge? e;
        for (int i = 0; i < _points.Count; i++) {
            e = Geometry.getEdgeFromPoints(_points[i], _points[(i + 1) % _points.Count]);
            e ??= (_points[i] + _points[(i + 1) % _points.Count]);
            _borders[i] = e;
        }
    }
#nullable disable

Any ideas on why this is happening and how to fix it?

north kiln
north kiln
frigid sequoia
dusty silo
dusty silo
frigid sequoia
#

Still does weird things with these values

north kiln
#

As I said, presumably (based on the limited info you have provided) b.connectedEdges is null. You cannot Intersect with null.

north kiln
eternal needle
frigid sequoia
#

Oh, ok, I see

grizzled zealot
#

If the parent is on a specific layer, are all the children automatically on the same layer if their layer is "Default"?

dusty silo
#

That worked, thanks.

north kiln
summer wedge
#

hi! how do you print a texture generated on runtime to png and avoid compression? i'm using this method but unity will downscale the image to the default 2048 when the texture is actually +5000px wide

    void SaveTextureAsPNG(Texture2D texture, string name)
    {
        // Ensure the texture is not null
        if (texture == null)
        {
            Debug.LogError("Texture is null. Please assign a texture.");
            return;
        }

        // Convert the texture to bytes
        byte[] bytes = texture.EncodeToPNG();

        // Define the file path using the provided texture name (in this example, saved in the Assets folder)
        string filePath = Path.Combine(Application.dataPath, name + ".png");

        // Write the bytes to a file
        File.WriteAllBytes(filePath, bytes);
    }```
rich adder
#

did you set it higher res in the texture importer?

summer wedge
rich adder
#

show how you create it

summer wedge
rich adder
summer wedge
#

i guess i should add an extra argument for compression size?

summer wedge
rich adder
#

forgot if thats a gpu limit

summer wedge
rich adder
#

or system

summer wedge
rich adder
#

oh cause I was reading wrong thing maybe

summer wedge
#

yee for x64 is double

rich adder
#

unity limits 16384 so its not that..

summer wedge
rich adder
summer wedge
#

? in the inspector, once the png is generated it seems to be proportionally downscaled to 2048 which is the default texture max size

rich adder
#

but if you're saying the file itself on hard drive is 2048 capped then nvm that

summer wedge
#

nah i mean it is not even just the compression option but like it actually downscales the texture, probably when EncodeToPNG?

rich adder
#

was checking but manual doesn't mention any limits of sorts

summer wedge
#

ahhhhhh

#

nvm no

#

oh yes

rich adder
#

fixed?

summer wedge
# rich adder fixed?

yes, i checked with the explorer and it has the right dimensions, but on the inspector it will show the compressed dimensions directly

#

i'm so sorry

rich adder
#

ahh nice..had a feeling lol

#

all good!

summer wedge
#

thanks!

cinder crag
#

im having a bit of a problem where im trying to combine the sliding and dashing statehandler daves code into one but idk how to do it without messing up with the sliding building up speed when sliding down a ramp , does anyone know how i can fix it?

also the vids if needed
https://youtu.be/SsckrYYxcuM?si=yUR_ATpbTYeIQCyp
https://youtu.be/QRYGrCWumFw?si=mVEcdJ93Ak0vKjIJ

ADVANCED SLIDING IN 9 MINUTES - Unity Tutorial

In this video, I'm going to show you how to further improve my previous player movement controller by adding an advanced sliding ability, that supports sliding in all directions, sliding down slopes and building up speed while doing so.

If this tutorial has helped you in any way, I would really ap...

▶ Play video

FULL 3D DASH ABILITY in 11 MINUTES - Unity Tutorial

In this video I'm going to show you how to code a full 3D Dash ability in Unity. Including dashing in multiple directions based on player input, keeping the momentum after dashing and adding camera effects to make the dash feel more alive.

If this tutorial has helped you in any way, I would r...

▶ Play video
rich adder
cinder crag
#

this was before adding the dashing

#

idk how to combine them so they dont mess with eachother

rich adder
#

not sure tbh

cinder crag
#

cause rn when im dashing , the speed doesnt instantly go away and lerps to the sprint speed or walk speed and when im sliding the speed doesnt build up as i slide down the ramp

#

so i think its confusing eachother

tender stag
#

if i have a physics material

#

with 0 friction

#

would the drag affect it?

teal viper
#

Drag is unrelated to friction.

tender stag
#

yeah i realised

#

i just solved my counter movement issue

#

i just increase the drag

#

instead of adding opposite forces like i did before

tender stag
winter frost
#

Hello everyone! How can I ask an Object to rotate the same way as another in the Y axis, without it being it's child? Thanks.

cinder crag
#

jsut did this

winter frost
rich adder
winter frost
#

Ok, thank you very much

tender stag
#

Land is called only once when the player lands and HandleLanding is in update

#

its not really smooth

#

if you played muck or any games made by dani then you know that when you land the camera like goes down and then up

#

giving the effect of more realistic landing

vale karma
#

how can i attach ids to animator values?

#

im trying to use animator.SetFloat(0, rb.velocity.z); and animator.SetFloat(1, rb.velocity.x); but its throwing an error on the first line

tender stag
vale karma
#

i tried that too, and it didnt work :/ same error

tender stag
#

well it has to

vale karma
#

MissingComponentException: There is no 'Animator' attached to the "Empty Player Controller" game object, but a script is trying to access it.
You probably need to add a Animator to the game object "Empty Player Controller". Or your script needs to check if the component is attached before using it.

tender stag
#

read the error

vale karma
#

i have the animator on a child object, am i referencing it wrong?

tender stag
#

how are you referencing it?

vale karma
#
using System.Collections.Generic;
using UnityEngine;

public class AnimatorValues : MonoBehaviour
{
    [SerializeField] private Animator animator;
    [SerializeField] private Rigidbody rb;

    private void Awake()
    {
        animator = gameObject.GetComponent<Animator>();
    }

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

    // Update is called once per frame
    void Update()
    {
        animator.SetFloat("animSpeedZ", rb.velocity.z);
        animator.SetFloat("animSpeedX", rb.velocity.x);

    }
}```
tender stag
#

yeah thats why

#

try this animator = gameObject.GetComponentInChildren<Animator>();

vale karma
#

ahhh okay, thankyou

tender stag
#

or just reference it normally

#

by dragging it in

vale karma
#

i figured using gameObject is for a game object not attatched to the object the script is on

tender stag
#

u dont even need the gameObject

#

u could even do animator = GetComponentInChildren<Animator>();

vale karma
#

yea i think i got in children and game object meanings mixed up

#

it fixed that issue, much more to follow

#

how is my rb.velocity.z value affected even if im not moving?

prime cobalt
#

Can I make a ui element a raycast target/not a raycast target in a script?

timber tide
#

usually there's a boolean right on those elements for that

final trellis
#

im gettin really strange behaviour with transform.LookAt in 2D, im trying to point this [image 1] gameobject's Y axis towards another object, in theory my code [image 2] should work, but instead of of the expected behaviour, the object in image 1 rotates along the X axis and makes the Y rotation -90 or 90 ( depending on the position on the object i want it to look at ) all instead of just rotating it along the Z axis

#

ive tried every single Vector 3 direction, none of which provide the correct result

#

ok so apparently transform.lookat sucks for 2d, hope unity one day releases a 2d lookat function

covert sinew
#

I'm having trouble finding the method to destroy an array that exists, then recreate it with a new index (or alter the index range of an existing array)

solar charm
#

sorry for the question but is there something wrong with this line? (line 72)

summer stump
solar charm
#

idk i downloaded it off the asset store 😭

summer stump
#

Check that your editor version is supported by the asset, and if it has any dependencies

solar charm
#

ok thanks ❤️

scenic shuttle
#

Can I post my code here and ask for advice?

solar charm
viral hemlock
#

what does the

normalized

do?

summer stump
loud python
#

Hey guys, do you notice anything wrong with this because its not working as Intended. https://paste.ofcode.org/75KTTditbqdQ33Zx6GmUxm . The intention is to Instantiate a InventorySlot into the Canvas>Inventory>Viewport>Content> (this is hwere it spawns the prefab). All is good with the instatiating of the prefab. The only problem is it doesnt set the itemWeapons Data as it instatiates the slot. Is there something im missing here? Here is a video https://gyazo.com/07f4e334402617476f190fabd079f4be not sure if you can see but when I transfer from the chest it just transfers the slot not the itemWeapons Icon. Not sure why.

final trellis
#

how do i make an object move along the Y axis, relative to its rotation?
this code makes it always go on the global Y axis rather than the local

final trellis
#

ah, thank you! :3

brittle trench
#

Hey guys, i wanted to have my game quit after the player gets a certain amount of points (ive set it to 1 temporarily so i can check quickly) but i cant get this code to work

#

This s a screenshot of the scoring system im not sure if im referencing it wrong in the gamemanager

summer stump
#

Oh, it's public static, that isn't good, but I guess you increase it directly somewhere else?

rich adder
#

those two are different variables btw

brittle trench
#

This one perhaps?

rich adder
#

if you want the static one you would need to call it from the class it belongs to

summer stump
#

Yeah, just about to say, theScore in GameManager is completely different than the one in ScoreSystem

brittle trench
#

ah

summer stump
#

Do not declase a theScore variable in GameManager at all
Reference it exactly like you do in CollectBottle

rich adder
#

also cache that Text component

#

GetComponent every frame is insane

#

no need to store scoreText as GameObject , you can store directly as Text

brittle trench
#

oo ok ill change that

#

thanks, i got the end game working

polar acorn
#

Oh man holy scroll lock that was an hour ago. Sorry for necroposting my discord didn't fetch new posts until after I sent it

summer locust
#

So im new to coding and setting up a basic movement system and have the jumping down but when going to side to side I gain more and more speed but I want a consist speed. I use rig2D.AddForce(Vector2.left * _walkingSpeed) is there any way i can keep using AddForce?

whole idol
#

After setting up VSC for Unity I always get this in front of every VSC file project I might try to run.

teal viper
teal viper
teal viper
teal viper
#

A lot of unnecessary stuff installed I see. I think Code Runner implements scriptcs and calls the command.

#

Honestly, I'd just use VS(not vs code) for unity, to avoid issues like that.

#

And C# in general.

whole idol
#

Im not using unity right now. Im just testing out c# on its own

teal viper
#

As I said "and C# in general"

whole idol
whole idol
barren violet
#

wait Did you make a new project or just a random .cs file in a folder?

teal viper
barren violet
#

There’s a wizard that walks you through it

pearl lodge
#

Did this change or am I missing something?

barren violet
whole idol
barren violet
barren violet
pearl lodge
#

No the error is: 'SceneManager' does not contain a definition for 'LoadScene'

barren violet
#

Add the namespace path to the static class if you want to have ambiguous class names

teal viper
pearl lodge
barren violet
timber tide
#

did you stick the box on another layer now

quick pollen
#

i dont get why you use a spherecast for checking ground

#

why not have a gameobject with a circlecollider

ivory bobcat
#

Some people can't view embedded discord text files. Consider posting !code using one of these two formats:

eternal falconBOT
quick pollen
#

also why are you crossposting @queen adder

pearl lodge
#

I didn't look at the code but is your 'box' tagged as ground/ground layer?

summer stump
#

I've been trying to figure out which one it is

summer stump
# quick pollen why not have a gameobject with a circlecollider

Usually you want to avoid that (unless you mean a child positioned at the feet, which is ok) because then you will be considered grounded when touching walls or ceilings.

But really, casting or overlaps are generally the best for ground checking imo. Spherecast is great, but I generally use raycasting

pearl lodge
summer stump
quick pollen
summer stump
#

People have this weird notion that casting every frame is expensive.

#

They really are not, especially ray and sphere.
Capsule and box become slightly more, but still EXTREMELY cheap

static bay
#

Sphere is pretty damn cheap, ya. It's one of the simplest queries you can do.

granite atlas
#

is there a way to like play as 2 people on one pc similar to roblox's

summer stump
#

Local multiplayer

granite atlas
#

yea how do i do that?

summer stump
#

Just have different input control different players

granite atlas
#

ok

half sparrow
#

I'm having some trouble with HTTP requests. I have a simple HTTP server running on my localhost on port 8888. My browser can access it just fine at 127.0.0.1:8888 but unity gives a 'Cannot connect to destination host' network error. Heres the code:

    {
        mouthMeshRenderer = GetComponent<SkinnedMeshRenderer>();
        StartCoroutine("RequestValue");
    }

    IEnumerator RequestValue()
    {
        UnityWebRequest request = UnityWebRequest.Get("127.0.0.1:8888"); //sends http request --> php script reads sql database
        yield return request.SendWebRequest(); //waits until request is done
        string requestString = "testing string";
        Debug.Log(request.isNetworkError);
        Debug.Log(request.error);
        if(!request.isNetworkError && !request.isHttpError)
        {
            
            requestString = request.downloadHandler.text;
        }
 
        Debug.Log(requestString);
    }```
#

I saw something about insecure urls being blocked on a support post but they didn't elaborate. Are simple ip addresses like this blocked in unity?

#

Oh also due to a package I need to use as part of the project, I'm on unity 2019.4

#

I realized I might need http:// on my url to make it work, but that returned a different error: Curl error 1: Received HTTP/0.9 when not allowed

#

Okay I figured it out. So http:// was needed, but also, on my actual HTTP server, I forgot to add 'end_headers()' to the get request code, which meant it didn't send a status code. The internal cURL doesn't like it when that happens and assumes its an old version of HTTP I think

scenic shuttle
#

Is using raycast in the "update" function OK and not burden performance?

timber tide
#

Go for it. Character Controller basically does a bunch of raycasting too

static bay
#

How are you attaching it to the hand?

#

_>

#

How? Are you making the cube a child of the hand though a script?

#

How is the PickupObject method being called?

#

It says 0 references above it.

#

Are you calling it from a Unity event or something? If not, you may just not be calling it.

#

Alright. Just to make sure, does the box follow the players movements when it's picked up? It's just not actually in the hand, right?

#

Does the box have a rigidbody and collider?

#

So in your PickupObject method, you're setting the cube's parent to be the hand, and resetting its rotation, which is good. The issue is you aren't setting the cubes position to be the same as the hand. It's moving with the player as a child should, but it's still offset from the hand.

#

Adding pickAbleObj.transform.position = handPlayer.position; should do it.

#

Though the cube may end up falling from the hand and onto the floor. If it does that, you'll need to shut off the Cube's rigidbody while its picked up, and turn it back on when you drop it.

#

also for DropObject you can do
pickAbleObj.transform.SetParent(null); instead of this

glass belfry
#

I cant open new project in unit 2022

#

how to fix it

static bay
#

Turn off the cube's box collider and rigidbody when you pick it up, and turn them on again when you drop it.

#
pickAbleObj.GetComponent<Rigidbody>().enabled = false;```
#

And then set them to true in DropObject

#

Or you just move the hand gameobject a bit.

#

What's happening is the box is so close to the player its "pushing" them.

#

but the box can't move

#

so it just keeps pushing them back

magic pagoda
#

I'm getting an error that says can not convert from "method group" to "string", how can I fix this?

simple sun
magic pagoda
static bay
#

no problem

ruby python
#

!code

eternal falconBOT
static bay
ruby python
#

Mornin' all.

I'm trying something a bit different (for me at least), but having issues with my 'Ship' controller.

https://streamable.com/hhd0vb

It's a very very very simple controller at the moment (basic forward back, no tweaking/lerping etc.), as you can see in the video I'm having a weird issue when I get to the poles of the moon. I'm not really sure why this is happening because in my head the ship should keep moving in the direction it's pointing, but it wigs out completely. Could anyone point me in the right direction please?

public class EagleController : MonoBehaviour
{
    [Header("Scene Paremeters")]
    [SerializeField] GameObject moonCenter;

    [Header("Keybind Assignements")]
    [SerializeField] KeyCode forwardKey = KeyCode.W;
    [SerializeField] KeyCode backwardsKey = KeyCode.S;
    [SerializeField] KeyCode turnLeftKey = KeyCode.A;
    [SerializeField] KeyCode turnRightKey = KeyCode.D;

    [Header("Eagle Physics Parameters")]
    [SerializeField] float moveSpeed;

    // Update is called once per frame
    void Update()
    {
        // Always point at center of Moon
        transform.LookAt(moonCenter.transform.position);

        //MyInput();
        if(Input.GetKey(forwardKey)) { 
            transform.Translate(Vector3.up * moveSpeed);
        }

        if (Input.GetKey(backwardsKey))
        {
            transform.Translate(-Vector3.up * moveSpeed);
        }
    }
}

Watch "2024-03-10 09-39-00" on Streamable.

▶ Play video
foggy crypt
#

Hello, I want to make something in Unity using coroutines.

I have a game project, where you should deliver "Pills" To your "Wife" because she is on timer.
I want the timer of "Wife" life to change when "Pills" are delivered to her by player.

Here's PlayerController code for this mechanic:

private void OnTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag("Pills"))
    {
        AudioSource.PlayOneShot(collect, 1f);
        ice.SetActive(true);
        hasPills = true;
        Destroy(other.gameObject);
    }
    if (other.gameObject.CompareTag("Wife") && hasPills)
    {
        AudioSource.PlayOneShot(deliver, 1f);
        hasPills = false;
        gameManager.wifeTimer += 50;
        ice.SetActive(false);
    }
}

Here's GameManager script for "Wife" Timer:

public IEnumerator WifeCountDown()
{
    yield return new WaitForSeconds(wifeTimer);
    mainCamera.enabled = false;
    gameOver.SetActive(true);
    gameOverCam.enabled = true;
}

For some reason when I change the WifeTimer variable - Coroutine variable doesnt change and it still count downs that number that it was when the Coroutine started.
Also, I have an UI timer on screen that counts down the WifeTimer and that number changes when "Pills" are delivered, but Coroutine WifeTimer doesnt change

How can I update the timer of the Coroutine?

magic pagoda
static bay
ruby python
foggy crypt
foggy crypt
#

I had this problem in my previous projects as well

ruby python
#

StopCoroutine(GameManager.CoRoutine) ??

timber tide
foggy crypt
# ruby python StopCoroutine(GameManager.CoRoutine) ??
if (other.gameObject.CompareTag("Wife") && hasPills)
{
    AudioSource.PlayOneShot(deliver, 1f);
    hasPills = false;
    gameManager.wifeTimer += 50;
    StopCoroutine(gameManager.WifeCountDown());
    ice.SetActive(false);
}

Coroutine is still running

foggy crypt
timber tide
# foggy crypt Can you maybe explain more? Please
public IEnumerator WifeCountDown()
{
    while (wifeTimer > 0)
    {
        wifeTimer -= Time.deltaTime;
        yield return null;
    }

    mainCamera.enabled = false;
    gameOver.SetActive(true);
    gameOverCam.enabled = true;
}```
foggy crypt
#

Will Yield Return change something?

languid spire
foggy crypt
timber tide
#

Is the problem the coroutine is ending and you don't want it to even though you're changing the time?

languid spire
#

show the line of code

foggy crypt
#
void Start()
{
    gameOverCam.enabled = false;
    StartCoroutine(WifeCountDown());
    StartCoroutine(gameCountDown());
timber tide
#

And if that's the case then what I said previously that you can't change WaitForSeconds if it's currently sleeping

languid spire
#

ok so you need to cache the Coroutine passed back from StartCoroutine and use that in the StopCoroutine

static bay
timber tide
#

once it sleeps it aint waking till it waits it out

ruby python
#

But yeah, I think the LookAt is an issue too.

static bay
#

So when you cross the pole it flips the ship around to point back to the center, then crosses the pole, then flips the ship around to point back to the center etc etc.

#

LookAt uses the world space up as a default.

#

So maybe providing the ships transform.up would help instead?

#

Not sure, rotations are a weak point for me.

ruby python
#

Yeah, trying a couple of different things. Thanks 🙂 And yeah, rotations always trip me up. lol.

static bay
#

But I definitely think it's related to how LookAt is rotating the whole ship when it passes the world up.

warm forge
foggy crypt
warm forge
#

Then you only have to call add timer and give a delegate

ruby python
warm forge
warm forge
#

If you need help you can pm me

foggy crypt
ruby python
static bay
#

Idk the ship aint flipping and the inspector says we're good.

#

So fuck it.

#

We ship it.

ruby python
#

Now to deal with the headache that is lerping and rotating left/right. lol.

foggy crypt
static bay
#

A low FPS/high velocity with your current set up can send the ship to bum fuck no where.

timber tide
ruby python
balmy bramble
#

does anyone know why it is saying rigidbody2d couldnt be found?

static bay
#

Cause your IDE is not configured

balmy bramble
#

how do i configure it?

static bay
eternal falconBOT
waxen inlet
static bay
#

Configure the IDE though regardless.

#

You want that formatting.

waxen inlet
modest dust
waxen inlet
#

that come with unity

ruby python
#

Okay, now I'm really confused. I've got this exact piece of code in another project and it works great, but on this new project my ship is just 'bouncing' back and forth (always trying to get back to 0, and I can't see why.

if (Input.GetKey(turnLeftKey))
{
    transform.Rotate(transform.forward * -turnLeftSpeed * Time.deltaTime);
}
modest dust
#

Visual Studio is the IDE

waxen inlet
#

idk

balmy bramble
waxen inlet
#

im stupid SOB

#

this is how it should be spelt

static bay
# waxen inlet idk

IDE stands for integrated development environment. Visual Studio is a type of IDE, ya. They're just the programs that let you edit/run code.

#

Visual Studio needs to be configured to recognize Unity.

waxen inlet
polar mica
#

Hey, good morning. I want to make a Game about balls falling down and everytime the ball hits a obstacle is should be counted and should get saved in a Variable in the ballprefab. At the End of the parkour the Value should get addet to another script like a moneysystem, which i already have. But if I spawn multiple balls the value gets overwritten? Can someone explain how i can solve this problem?

#

I then send the value to another script via an instance

gaunt ice
#

what values got overwritten?

static bay
#

And the Value in the new OnContact starts at 1.

#

Thus, it gets "reset".

#

Those other OnContacts still exist, but they're no longer what that Instance variable is pointing to.

modest dust
#

Perhaps what you want is a static Value, not a static Instance.

polar mica
static bay
gaunt ice
#

or store the variable in other singleton

static bay
polar mica
#

Ok thank you, i will try it

ruby python
verbal dome
minor patio
#

Tell me a story about initialising components, daddy...
I have a component attached to a game object, but the fields in that component remain null

verbal dome
#

Like how do you define them or how do you assign a value to them

proven herald
#

Does anyone have an utility method (or could tell me how) to convert a Color to an HDR color at runtime providing an intensity? leaning towards Color Mutator

minor patio
#

https://youtu.be/HRLdcMil7Ec?si=MWDMu3UW7BEWlO8M
as an aside
@verbal dome so far I've initialised them with the standard 'x = new ({class} (class field))', but that's still returning null

Download the source code: https://www.patreon.com/posts/source-code-for-88052099
We've all been there: You design a slick C# method, but then it might need to return... null. How many times have you crafted a method, sometimes a complex one, only to encounter the inevitable predicament of possibly returning null?
The ripples from this single dec...

▶ Play video
#

I get the impression that I'm missing a lot
I had a semi-functional house-of-cards last week XD

odd widget
#

to destroy a gameobject (monster) is it better to check the health on the Update() or is it better to do it when doing the damage calculation?

minor patio
#

the offending code:
public Feature Ambition { get; set; }
public Feature Vitality { get; set; }
public Feature Nous { get; set; }
public Feature Mystique { get; set; }
public Feature Might { get; set; }
public Feature Grace { get; set; }
public Feature Humour { get; set; }
public Feature Habit { get; set; }

public Representative()
{
Ambition = new Feature(FeatureTitle.Ambition);
Vitality = new Feature(FeatureTitle.Vitality);
Nous = new Feature(FeatureTitle.Nous);
Mystique = new Feature(FeatureTitle.Mystique);
Might = new Feature(FeatureTitle.Might);
Grace = new Feature(FeatureTitle.Grace);
Humour = new Feature(FeatureTitle.Humour);
Habit = new Feature(FeatureTitle.Habit);

 // Assign the initialized features to the provided _features array
 features = new Feature[8];

 features[0] = Ambition;
 features[1] = Vitality;
 features[2] = Nous;
 features[3] = Mystique;
 features[4] = Might;
 features[5] = Grace;
 features[6] = Humour;
 features[7] = Habit;

}

#

oops - I hate when that happens

#

the get & set properties are getting references in the editor, but the Representative constructor got nothing

minor patio
#

yeah

verbal dome
#

You should not use constructors with MonoBehaviours (or other UnityEngine.Objects).
Use Awake and/or Start for initialization instead

#

Also you could can use an initializer with a property: public Feature Ambition { get; set; } = new Feature(FeatureTitle.Ambition);

minor patio
#

thanky

verbal dome
minor patio
#

my bad - it looked interesting to my learning

proven herald
#

So I have theses 2 methods in a Utility

public static Color PercentageToColor(float percentage, Color minColor, Color maxColor) {
            return Color.Lerp(minColor, maxColor, percentage);
}        

public static Vector4 ConvertToHDR2(Color color, float intensity) {
            return color * Mathf.Pow(2,intensity);
}

And I call them in an update like this, goal is to change a material's emission color over time

private void Update() {
            var percentageAsColor = ColorsUtility.PercentageToColor(
                GetComponentInParent<TowerController>().GetMaintenanceLevel(),
                GameTheme.positiveColor,
                GameTheme.negativeColor
            );
            
            _material.SetVector(
                EmissionColor,
                ColorsUtility.ConvertToHDR2(percentageAsColor, 4f)
            );
}```

Issue is that although the intensity is always set to somewhere around 4f, it's not exactly 4f as it would be setting it in inspector. and also the intensity value goes down over time. noticed it start at 4.7f and ended up at 3.9f, any idea what's wrong or the proper way to do this?
low estuary
#

hello, can i recieve help from guys who now unity2D on this server, because i have a small problem and am new to the dev game

ivory bobcat
ivory bobcat
# low estuary hello, can i recieve help from guys who now unity2D on this server, because i ha...

https://dontasktoask.com/

The solution is not to ask to ask, but just to ask. Someone who is idling on the channel and only every now and then glances what's going on is unlikely to answer to your "asking to ask" question, but your actual problem description may pique their interest and get them to answer.
This is the beginner coding channel. If it's related to coding, you should ask here else try #💻┃unity-talk

smoky granite
#

can someone help me with a tiemr? so i want to make a 3 hit based combo and im assuming the main premise of it is that

if hit 1 is 1f and press "fire1" then play anim for hit 2

but i dont know how to make it a timer. the timer would preferably be like 2 secconds for each hit and if the button doesn't get pressed its back to idle position.

here is my relevant code so far:
`public void attack()
{
if (Input.GetButtonDown("Fire1")&& IsGrounded())
{
hugo.GetComponent<Animator>().Play("HguoFire1");
attacking = 1f;

}

}`

ivory bobcat
smoky granite
ivory bobcat
languid spire
#

how do you test for Ground?

pallid sand
#

Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreenMode == FullScreenMode.FullScreenWindow); Debug.Log($"resolution height {Screen.currentResolution.height} and width {Screen.currentResolution.width}");

#

this is my code to change resultion but it's not working in build or editor always debug same resultion

languid spire
#

maybe make your Box not Ground but add a Plane to the top of the Box which is Ground

#

I can only supply answers to the questions asked, I'm not a mind reader

#

of course there is, but are you ready for such complexities?

#

so you write your own collision code and use the normal of the contact to decide what to do about it

smoky granite
#

can someone help? basically i have a timer for this system im doing and im trying to make it so when i let go of the fire button the float goes to 0f slowly from when poressing it 5f.

here is the relevant code

`public void Attack()
{
if (Input.GetButtonDown("Fire1") && IsGrounded())
{
attacking = 5f;
hugo.GetComponent<Animator>().Play("HguoFire1");
}
if (Input.GetButtonUp("Fire1") && IsGrounded())
{
attacking -= Time.deltaTime;

}

}`

languid spire
smoky granite
#

wait

#

thats made something click in my brain

#

i knew hat but

#

im so dumb wtf

ruby python
#

!code

eternal falconBOT
ruby python
#

public class EagleController : MonoBehaviour
{
    [Header("Scene Paremeters")]
    [SerializeField] GameObject moonCenter;

    [Header("Keybind Assignements")]
    [SerializeField] KeyCode forwardKey = KeyCode.W;
    [SerializeField] KeyCode backwardsKey = KeyCode.S;
    [SerializeField] KeyCode turnLeftKey = KeyCode.A;
    [SerializeField] KeyCode turnRightKey = KeyCode.D;

    [Header("Eagle Physics Parameters")]
    [SerializeField] float moveForwardSpeed;
    [SerializeField] float moveBackwardSpeed;
    [SerializeField] float turnLeftSpeed;


    // Update is called once per frame
    void Update()
    {
        transform.LookAt(moonCenter.transform.position, transform.forward);

        //MyInput();
        if (Input.GetKey(forwardKey)) { 
            transform.Translate(Vector3.up * moveForwardSpeed);
            
        }

        if (Input.GetKey(backwardsKey))
        {
            transform.Translate(-Vector3.up * moveBackwardSpeed);
        }

        if (Input.GetKey(turnLeftKey))
        {
            transform.Rotate(transform.forward * -turnLeftSpeed * Time.deltaTime);
        }

        if (Input.GetKey(turnRightKey))
        {

        }
    }
}

#

Full code, just in case I'm missing something really obvious (and yes I know it stupidly simple etc. lol)

languid spire
#

Please use the 'Large Block' option for code longer than a few lines

ruby python
#

My bad, never really sure what the 'cutoff' is for large/small blocks.

verbal dome
languid spire
#

basically, imo, anything less than 10 lines is ok for inline, more than that should be in a paste site

ruby python
ruby python
languid spire
verbal dome
verbal dome
languid spire
ruby python
#

I'm only using the collision to detect when the ship has landed and trigger an animation. @languid spire there is a rididbody on the ship. I'm just not using it for movement

languid spire
ruby python
#

Okay.

steel smelt
#

Why?

languid spire
#

because otherwise they will fight and screw up

verbal dome
#

Moving via transform will not really notify the physics system and make it detect collisions

steel smelt
#

His RB could be kinematic. PhysX will sync with transforms at the beginning of the first physic step for the frame

languid spire
#

kinematic is different, but afaik, that is not the case here

craggy laurel
#

I am looking for a UI feature which I know exists but forgot how to implement:

  • I have 2 UI elements (say a Character and a Square)
  • The square limits how much I can see of the Character - outside of the Square, the Character is invisible
  • When the square gets bigger, I can see more of the underlying Character

Can someone help out?

ruby python
#

Image Mask

craggy laurel
#

thanks!

languid spire
#

or Sprite Mask

craggy laurel
#

Sprite Mask for WorldSpace right?

languid spire
#

yes

verbal dome
#

99% not a unity issue

atomic star
#

My animator is not playing the default "Flying" animation please help I am getting it using GetComponent<Animator>() in Start() of my character script but it's still not working I am also calling animator.play("Flying") i get no errors and no null exception but the animation just does not play.

#

the name of the idle state in animator is correct

ruby python
#

Could be wrong, but you animation speed is set to 0 (top left of your first image)

atomic star
#

omfg i feel so dumb

ruby python
#

Nah, easy to overlook, especially if you've been looking at it for a while.

atomic star
#

i had set it to 0 cause i thought it was for sample rate at first but then i found it and never switched it to 1

#

Thank you! <3

ruby python
#

No probs. 🙂

#

Okay, so I've re-written my controller, but am now stuck on something. lol.

Originally I had the ship always pointing to the center of the moon using LookAt. But now that doesn't work (because, physics. lol.). And I'm a little stuck on how to keep the ship perpendicular to the surface of the moon and maintaining the same height (I don't need/want to move the ship 'up and down).

https://pastebin.com/DvqHxGA1

Would anyone have any ideas? ((Image for Illustration))

silent vault
#

Hello, small question regarding AI and triggering their behavior. If I want to detect if an AI needs to shoot at a player, is it better to use colliders or to check the distance in an update method? Which one more performant if I'll end up have dozens of such AI in the map?

#

I've checked several tutorials and their code varies. Sometimes it's a collider, sometimes it's an update. Not sure which one is better at the moment

verbal dome
languid spire
#

Collider will always be more performant than a RayCast in Update

verbal dome
#

ConfigurableJoint can do that at least @ruby python

#

Or you can manually add torque to rotate towards the desired rotation, but I think thats more complex

ruby python
fleet breach
#

Hello i have a problem in my thingg ;-;

#

I cant assign the AR session game object to the raycastmanager

#

I did copy paste the exact script too

verbal dome
#

ARRaycastManager

silent vault
fleet breach
#

wait can i show u the code ?

silent vault
#

Vector3 playerDirection = agent.target.transform.position - agent.transform.position; if (playerDirection.sqrMagnitude > agent.config.initChaseDistance * agent.config.initChaseDistance)

fleet breach
#

im all new to this so yk

#

this is for my uni project ;-;

verbal dome
#

Well you dont have the component that you are trying to drag in 🤷‍♂️

ruby python
fleet breach
silent vault