#đŸ’»â”ƒcode-beginner

1 messages · Page 171 of 1

north kiln
#

read???

wary olive
#

Why would you want to wait 2 seconds for nothing after it? Coroutines are used when you need to delay an action

clear seal
north kiln
clear seal
north kiln
#

Then surely you can answer your own question

summer pulsar
#

hello, im trying to make a bool called alive set to false from the component "PlayerMovement", when the int player health reach 0 from the component "PlayerHealth" but it doesnt work, any help ?

north kiln
summer pulsar
clear seal
summer pulsar
wary olive
#

Ah the joys of programming ✹

astral urchin
#

can someone help with this

eternal needle
eternal needle
signal bronze
#

It works perfectly thanks @slender nymph and @rocky canyon for your help, i appreciate it a lot, thanks fr

scarlet skiff
clear seal
#

weirdly my conon does not shoot on trigger

#

oh wait hold on

frigid sequoia
#

Simple question: how do I get a reference to an image?

green copper
#

is there a way to link objects such that if I make a change to one, it makes a change to all?

frigid sequoia
#

Like, it doesn't let my assing it on the inspector

#

Why it doens't show?

clear seal
wary olive
# frigid sequoia

Is there an error in ur script? It may not update the inspector until it can build

green copper
clear seal
frigid sequoia
frigid sequoia
#

It is just not managing any reference to the Image class

clear seal
wary olive
frigid sequoia
frigid sequoia
eternal needle
clear seal
wary olive
frigid sequoia
clear seal
#

or

#

wait no

wary olive
clear seal
#

it should say image

clear seal
wary olive
#

Like image2, but that isn’t in your screenshot which is why I’m asking if you have compiler errors or haven’t saved etc

frigid sequoia
wary olive
frigid sequoia
#

I use caps so none misses it, I am not mad :p

frigid sequoia
slender nymph
#

also chill tf out

wary olive
clear seal
slender nymph
wary olive
#

I think his issue is that image (game object) shows in inspector but image2 (image) doesn’t? His naming makes it very confusing

wary olive
clear seal
#

@frigid sequoia what do you want to use it for

summer pulsar
#

hello, so i have this spawner but the problem is if i set the prefap as a reference it will only follow my player first position but if i make the reference as an object in the hierarchy it will constantly follow the player but if i destroyed the original referance i get an error, any help?

frigid sequoia
#

There, that's the actual code I am using, I only did the last one to make it clearer, but apparently did the opposite

frigid sequoia
#

The image List is not showing

clear seal
frigid sequoia
#

Nor can I get the reference through code

clear seal
#

UI?

frigid sequoia
#

Am I calling it wrong?

north kiln
wary olive
north kiln
#

You are not using it in practice, so it shouldn't be in your code

clear seal
frigid sequoia
slender nymph
frigid sequoia
clear seal
#

it need to be sprite2d and ui

wary olive
timber tide
#

It would be like Image.sprite right

frigid sequoia
#

This image

north kiln
tropic agate
#

No, I have some experience with coding and unity, but i dont think its that good with unity

clear seal
#

@frigid sequoia ?

wary olive
#

That’s not their issue, the issue is the code, it needs to import UnityEngine.UI not UIELEMENTS

north kiln
#

I am concerned that the code apparently compiles, because it really shouldn't

frigid sequoia
clear seal
frigid sequoia
#

If I am calling a reference that I am not using shouldn't do anything

wary olive
#

It’s not showing in the inspector

frigid sequoia
wary olive
#

The actual image they wanna put in doesn’t affect the code not showing the field in inspector

north kiln
slender nymph
north kiln
#

How would this compile?

#

Image is not a component, how could they get it?

slender nymph
#

GetComponent has no generic constraints

north kiln
#

Oh, I suppose it's a... yeah

frigid sequoia
#

Then what the heck should I be calling?

wary olive
#

Change UIELEMENTS to UI

frigid sequoia
slender nymph
# scarlet skiff pls..

have you used the debugger to step through your code and figure out where your logic is going wrong yet?

timber tide
# summer pulsar

If you want to make improvements to the code I suggest just taking out FindGameObjectsWithTag and just add the reference to the player on the enemies

frigid sequoia
#

Why does that work though? Like I don't undertand

wary olive
slender nymph
north kiln
#

God it's gonna be good when UGUI gets thrown to the fire

frigid sequoia
#

I literally didn't reference anything, it just added it automatically

north kiln
#

Because you approved of it

#

You accepted that namespace

frigid sequoia
#

But why is that the default?

slender nymph
frigid sequoia
#

Like wtf?

wary olive
#

It isn’t, you would’ve been given two options

north kiln
#

There is no default

scarlet skiff
north kiln
#

Also, there is nothing wrong with UIElements, I am using it and not using UGUI

scarlet skiff
#

i got no clue where to go fro mthere

summer pulsar
frigid sequoia
#

Still, if I am calling an Image from Elements, how come that it doesn't show in the inspector?

north kiln
#

UIElements' VisualElements are not serializable by Unity. They are not scene objects, or configurable via the inspector.

slender nymph
timber tide
clear seal
#

why doesn't my canon shoot

north kiln
#
  1. Confirm your code is actually running
scarlet skiff
summer pulsar
clear seal
#

wdym by that

north kiln
#

Use the debugger or logs

summer pulsar
wind escarp
timber tide
#

the problem you're having is setting the prefab data of the enemy to follow the player prefab instance which does not exist in the scene as of yet (it's just a template of data which you instantiate later into the game)

#

so if you want to spawn enemies dynamically, you need a runtime way to figure out what target there is to chase on the scene

summer pulsar
timber tide
#

Ignoring what I said previously about using FindGameObjectsWithTags, you can use this to find the player reference too if you choose to do it that way

#

I usually avoid those methods because it requires searching throughout the scene hierarchy, but you're better off having a manager component/singleton/static ref to grab the current player reference.

charred axle
#
using System.Collections.Generic;
using UnityEngine;

public class RandomSpawns : MonoBehaviour
{

    public GameObject[] animalPrefabs;
    private float spawnRangeX = 10;
    private float spawnPosZ = 10;
    // Start is called before the first frame update
    void Start()
    {
        // Makes it so it spawns randomly at xx speed
        InvokeRepeating("SpawnAnimal", 2, 1.2f);

    }

    // Update is called once per frame
    void Update()
    {

    }


    void spawnAnimalLeft()
    {
        // Pulls the element from Prefabs
        int animalIndexLeft = Random.Range(3, 4);
        // Randomizes the position
        Vector3 spawnPos1 = new Vector3(10, 0, Random.Range(2.0f, 12.0f));
        Instantiate(animalPrefabs[animalIndexLeft], spawnPos1, animalPrefabs[animalIndexLeft].transform.rotation);
    }
    void SpawnAnimal()
    {
        // Pulls the element from Prefabs
        int animalIndex = Random.Range(0, animalPrefabs.Length);
        // Randomizes the position
        Vector3 spawnPos = new Vector3(Random.Range(-spawnRangeX, spawnRangeX), 0, spawnPosZ);
        // Randomizes the position
        Vector3 spawnPos1 = new Vector3 (10, 0, Random.Range(2.0f, 12.0f));


        // Spawns the animals
        Instantiate(animalPrefabs[animalIndex], spawnPos, animalPrefabs[animalIndex].transform.rotation);
    }

}

Following the official unity tutorial, my 3 and 4 prefabs spawns on random X coords even though I wrote 10.

    {
        // Pulls the element from Prefabs
        int animalIndexLeft = Random.Range(3, 4);
        // Randomizes the position
        Vector3 spawnPos1 = new Vector3(10, 0, Random.Range(2.0f, 12.0f));
        Instantiate(animalPrefabs[animalIndexLeft], spawnPos1, animalPrefabs[animalIndexLeft].transform.rotation);
    }```

--

```Vector3 spawnPos1 = new Vector3(10, 0, Random.Range(2.0f, 12.0f));```
north kiln
eternal falconBOT
north kiln
#

Also, SpawnAnimal uses spawnPos not spawnPos1, which you just don't use in that method at all. spawnAnimalLeft is never called.

meager raptor
#

asked a few people but no one's been able to solve it yet,

my purpose: when unit is clicked, highlight should appear

my problem: that doesn't happen.
i drew around the issue in red.
it's definitely in the red i drew cuz i made debug logs for other parts of the code like the raycasting and that worked fine
EDIT: no debug log message appears in console when i click on unit

any help would be appreciated ive been on this for a while now

short hazel
#

You're not calling SpawnAnimalLeft at all here, indeed

charred axle
#

ah saw it, 1 second

#
    void spawnAnimalLeft()
    {
        // Pulls the element from Prefabs
        int animalIndexLeft = Random.Range(3, 4);
        // Randomizes the position
        Vector3 spawnPos1 = new Vector3(10, 0, Random.Range(2.0f, 12.0f));
        Instantiate(animalPrefabs[animalIndexLeft], spawnPos1, animalPrefabs[animalIndexLeft].transform.rotation);
    }
    void SpawnAnimal()
    {
        // Pulls the element from Prefabs
        int animalIndex = Random.Range(0, animalPrefabs.Length);
        // Randomizes the position
        Vector3 spawnPos = new Vector3(Random.Range(-spawnRangeX, spawnRangeX), 0, spawnPosZ);
        // Randomizes the position


        // Spawns the animals
        Instantiate(animalPrefabs[animalIndex], spawnPos, animalPrefabs[animalIndex].transform.rotation);
    }

}
``` am i on the right track
frigid sequoia
short hazel
#

If you want it to spawn at a constant X position, this won't do it, you still choose a random X for spawnPos

#

And as far as I can see, void spawnAnimalLeft() is still left unused

#

You only schedule the execution of SpawnAnimal() in Start()

green copper
#

I'm trying to programatically generate an inventory grid, but all of the sprites are generated with a scale of 240. The object holding the generation script has a scale of 1, 1, 1

#

I know this will generate all sockets in the same place currently, I'm trying to solve the scale problem first

north kiln
#

(Instantiate has an overload that sets the parent, you don't need to do it in two steps)

charred axle
#

i am so lost

north kiln
short hazel
#

Consider using nameof(spawnAnimalLeft) instead of a string - gives you additional safety as the compiler checks that what you pass in nameof actually exists

charred axle
#

oh

#

DID IT!

#

ty guys

timber tide
#

Is it UI? Is it SpriteRenderers? Who knows

north kiln
#

I might as well just repeat myself for all I know

charred axle
#

int animalIndex = Random.Range(0, 2);

(0 , 2) shouldn't include these first 3?

charred axle
#

ty

short hazel
#

Maximum exclusive for random range with int values

#

So you get either 0 or 1 here

charred axle
#

oh so it should be 0, 3?

short hazel
#

Yes. But why not use the whole list here?

green copper
frigid sequoia
#

I think the max in the range is exclusive precisely to work with Lists

short hazel
#

Random.Range(0, animalPrefabs.Length)

charred axle
north kiln
charred axle
#

i couldnt have thought any other way to do it tbh

polar acorn
short hazel
#

Two lists/arrays?

#

Easier to manage if you suddenly want to add another element, and want it to spawn without altering the code at all

north kiln
green copper
#

but anything I try is read as not a valid name

green copper
#

the type or namespace is not found

north kiln
#

Then include the namespace

#

Is your IDE configured?

#

It should suggest things as you type

polar acorn
#

Also, it's not "The gameObject is an Image object", it's a GameObject that has an Image Component on it

polar acorn
north kiln
#

and give you namespace suggestions if you get errors regarding namespaces

green copper
green copper
frigid sequoia
#

Guys, I know this question is kinda abstract, but how do IEnumerators work?

clear seal
#

idk if this is code related but why my canon ball just fall of

polar acorn
green copper
#

My error is now that the object I want to instantiate is null

polar acorn
green copper
frigid sequoia
timber tide
#

coroutines are mini update loops

frigid sequoia
#

Like, what should I place in the if? I have been stuck there for a while now XD

polar acorn
green copper
north kiln
polar acorn
# green copper

If you are getting an error saying this Instantiate is the one with the error, then there exists a mainInvInstancer without a socketPrefab set

frigid sequoia
north kiln
#

Yes

polar acorn
north kiln
#

It runs once per call, and each yield is just a place for the state machine to continue from next Update/(other time)

green copper
polar acorn
#

Start doesn't run again when the object is disabled

#

then there'll be plenty of time for someone to see it and respond to it

north kiln
#

Cool, well it's not relevant here, and you shouldn't cross-post. So don't

charred axle
north kiln
#

You aren't getting the point: don't cross-post, and don't argue about it

green copper
north kiln
#

Then wait like everyone else

ripe shard
#

people who care about mobile look into mobile, if nobody looks into mobile, nobody cares about mobile and consequently your mobile problem, that wont change if you put your problem into other channels.

frosty hound
#

Also generic gradle errors are impossible to debug without diving into the project with someone. Who has that time?

swift crag
#

yes, you need to actually read the error messages and do some research

north kiln
#

Imo someone should just make a site like mine specifically for gradle errors

#

surely they're all solved problems

#

I just don't give two shits about mobile so 100% could not be bothered 😄

ripe shard
#

dealing with mobile in your free time is a special kind of masochism 😛

frigid sequoia
#

Can I like do something like this....

#

Does this work then?

astral urchin
frigid sequoia
clear seal
#

i made a canon and my ball keep clipping why?

eternal needle
frigid sequoia
clear seal
frigid sequoia
clear seal
frigid sequoia
#

And you want it to collide with a surface with a collider?

clear seal
#

clearly pls

frigid sequoia
#

Should work with just that

clear seal
#

oh ye

frigid sequoia
#

If you are using external methods to move stuff, just as Translate in code, it will always clip through

#

Since it is not using physics

clear seal
#

hold on

astral urchin
#

followed a tutorial to make the mesh deform when the ray hits the mesh, the input side is working but this deforming code isn't and idk why since I followed the tutorial

clear seal
frigid sequoia
# clear seal it uses physics

If you are moving all with physic and you have rigidBody it should collide with all colliders that are not set to be trigger colliders. Have you double checked everything?

clear seal
#

it's supposed to shoot with rigidbody

#

the problem is that idk if it's my computer who loads while it's shooting or if it's a problem

zinc grove
#

Is it possible to make a sprite look different from 2 different cameras? For example I have 2 players playing chess so their views are from 2 different sides One of the players boards looks correct while the other all of the sprites for the pieces are upsidedown any idea on how to correct this from the camera view or will I have to do something else?

teal viper
zinc grove
# teal viper Is it like sprites in 3d space?

Im making a 2d chess game I might not understand what your asking but let me know if this answers it I have a 8x8 board with tile objects that have sprites attached that show the pieces and when they move the sprites get cleared and put where they need to be. I was just looking to see if I could change the visual through 2 different cameras to be rotated 180 degrees so both views look correct.

#

I guess the same thing would work for the move previews to only show it on the side that is actually moving aswell

meager raptor
#

hi guys does anyone know what this green plus means in the highlight for the playercommander? the playercommander is a unity asset and the cube is just a 3d object i created

swift crag
#

the + indicates that you've added an object to a prefab instance

#

notice that PlayerCommander has a blue box next to it

#

A solid blue box is a prefab.
A blue box with a stripe on top is a prefab from an asset (oftentimes a model)

#

Unity tracks all of the changes you've made to the prefab instance. You can apply them to the prefab or revert them if you want.

#

for example, I've attached two spot lights to this model

meager raptor
#

ah okay that makes a lot of sense, appreciate it

swift crag
#

Overridden properties will show up as bold and get a blue line next to them in the inspector

#

er, at least they get a blue line. maybe i'm just imagining the boldness

teal viper
tall basalt
#

how can I change directional light color at runtime?

I tried this didn't work

Lights[1].color = Color.Lerp(new Color(117, 229, 255), new Color(60, 117, 202), foglerp);

charred axle
#
    {
        hungerSlider.maxValue = amountToBeFed;
        hungerSlider.value = 0;
        hungerSlider.fillRect.gameObject.SetActive(false);
        gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
    }```
swift crag
#

Your colors are wrong

rich adder
#

you're using color

swift crag
#

They take floats in the 0..1 range

charred axle
rich adder
#

which is 0-1

#

color32 is the bytes

rocky canyon
#

Color32 is what ur looking to do

rocky canyon
swift crag
#

I'd just calculate the correct values and use Color, but you could definitely use Color32 if you want to keep the 0-255 values

rocky canyon
#

or GameManager cant be found.. unsure tbh

rich adder
#

color32 is more performant afaik

swift crag
#

it's going to get turned straight back into a Color

rich adder
#

is it ? hm weird they recommend Set/GetColor32 but turn into floats for color

tall basalt
#

I tried this still not working

Lights[1].color = Color32.Lerp(new Color32(117, 229, 255, 255), new Color32(60, 117, 202, 255), foglerp);

rich adder
tall basalt
# rich adder show the whole context of this line

Lights[] is an array of directional lights
foglerp is a float

running this in update
foglerp += Time.deltaTime * lerpSpeed;
Lights[1].color = Color32.Lerp(new Color32(117, 229, 255, 255), new Color32(60, 117, 202, 255), foglerp);

teal viper
teal viper
teal viper
rich adder
teal viper
tall basalt
rich adder
teal viper
#

Ok, so, it's not "not work", it's a freaking compile errors. Please mention that first...

teal viper
tall basalt
#

Directional Light

teal viper
#

Can you share the whole script?
!code

eternal falconBOT
rich adder
#

lol they def used the struct DirectionalLight

#

instead of Light

teal viper
#

Seems like it

teal viper
tall basalt
tall basalt
teal viper
tall hill
#

does anyone know how to create a good isometric char controller

frosty hound
#

Create a normal character controller and just angle the camera thinksmart1

teal viper
frosty hound
#

Yeah, that lol

teal viper
#

Oh. I see. I thought it was among the standard set or the unity server one.
Thanks!

frosty hound
#

Maybe we can add it 😏

rocky canyon
#

lol, that'd be the new hotness for sure 😄

tall hill
frosty hound
#

Use Cinemachine to do that

craggy oxide
#

halp pls

#

says that + can't be applied to Quarternions and Vector3

teal viper
#

It can't.

craggy oxide
#

obviously my method of changing the camera rotation is just wrong so I'm asking for an alternative

#

i thought it'd be the same as changing camera position

timber tide
#

if only

teal viper
#

Rotation != Position

craggy oxide
#

so what do I do

wintry quarry
craggy oxide
#

alr thanks

#

unity courses messing me up lmao

#

this is the 2nd course where they're like "okay fix these bugs we wont tell you how to do it"
which is fine because we learnt everything before
except for changing camera rotation in C# theres nothing about that yet so im left in the dark

#

im not even gonna ask what a Quarternion or Euler is, i know its some complex math shi

#

unless you could explain it in simple terms

eternal needle
#

Euler is something you should probably know already, unless you are very young

craggy oxide
#

nah it wasn't part of our curriculum

#

cause nationally we're stupid

#

i'm 17 btw got a B as my final maths grade so yknow not bad

#

never heard of Eulers

timber tide
#

I would suggest just using angle axis for stuff like the camera, but it's probably fine if you want to use euler. It's just when you're doing more rotation other than a single axis does euler become a little janky

wintry quarry
eternal needle
wintry quarry
#

Quaternions are how Unity actually represents rotation

#

(Euler angles are named after a mathematician Leonhard Euler)

#

Same one as the mathematical constant E aka Eulers number

craggy oxide
#

err

#

yeah

craggy oxide
timber tide
#

it's more relevant in like college algebra

craggy oxide
#

good thing I didn't take that 😎

#

my friend took maths, additional maths and further maths

#

what the hell was he thinking

#

he's hating life rn

scenic cipher
#

I'm trying to smooth my player's movement but SmoothDamp() doesn't seem to be working correctly, I must be doing something wrong.
I'm trying to make the smoothing take a second, but it ends up taking around 7 seconds. Any idea why?

    private float smoothedX = 0f;
    private float smoothedZ = 0f;
    private float smoothVelocityX = 0f;
    private float smoothVelocityZ = 0f;

    void Update()
    {
        float x = Input.GetAxisRaw("Horizontal");
        float z = Input.GetAxisRaw("Vertical");

        smoothedX = Mathf.SmoothDamp(smoothedX, x, ref smoothVelocityX, 1f);
        smoothedZ = Mathf.SmoothDamp(smoothedZ, z, ref smoothVelocityZ, 1f);
    }```
clear seal
#

i made a canon and if i want to rotate it, should i do it with GetKey input and then i use transform.rotate or is there an other way to do so

swift crag
#

If you're just rotating left and right as long as the key is held down, then that sounds reasonable.

#

If you want to limit the rotation, I'd suggest this...

#
[SerializeField] Quaternion leftLimit;
[SerializeField] Quatenrion rightLimit;
[SerializeField] float turnRate;

void Update() {
  if (Input.GetKey(KeyCode.A))
    transform.rotation = Quaternion.RotateTowards(transform.rotation, leftLimit, Time.deltaTime * turnRate);
  if (Input.GetKey(KeyCode.D))
    transform.rotation = Quaternion.RotateTowards(transform.rotation, rightLimit, Time.deltaTime * turnRate);
}
#

This will rotate towards the leftLimit or rightLimit rotations by turnRate degrees per second.

#

I find this to be a lot more reliable than messing with euler angles

#

you constantly get footgunned by how they wrap around

craggy oxide
#

oki these unity courses have got me on a good path so far
i'm pretty happy now

#

just wanted to say that :D

frigid sequoia
#

Still you learn a lot and it is cool, just not as engaging I would say

long lantern
#

Can I have some help with my code I'm makeing a flappy bird games and I've got a error and know idea what it could be

frigid sequoia
#

I don't say this to discourage you, quite the opposite; I want you to know that the same happened to me and I pushed on and I don't regret it in the slightest, just don't give up 😄

frosty hound
eternal falconBOT
#

mad No

Be mindful, if someone requests your code as text, don't send a screenshot!

frosty hound
#

You can use !code to share your code

eternal falconBOT
frigid sequoia
# long lantern

-= is an opperation, not a declaration, you cannot initialize the value like that

#

You are telling it to subtract from something that doesn't exist

long lantern
#

Is there anyway to fix it

frosty hound
#

Remove the -

summer stump
clear seal
#

and easier

long lantern
#

Omds I'm so stupid I've only been codeing since today and didn't realise I put that there

#

Mb

frigid sequoia
#

I think you don't even need to use the = 0 at all, a primitive value is 0 by default

swift crag
#

Fields are initialized with their default value.

#

And indeed, for int, default is 0

#

(default is, literally, the default value for a given type)

#

local variables are not initialized automatically, so you do have to give an explicit value

frigid sequoia
#

Is there any reason for that?

swift crag
#

Probably because it would require an enormous amount of...

public Foo whatever = null;
#

You can't reason about whether a field will be assigned before it's used because you can use an instance of the class well after it's created

#

vs. a local variable, which you explicitly create and then use

frigid sequoia
#

So it would try to initialize all values even though the process path doesn't need them at all...

swift crag
#

The compiler needs to be able to prove definite assignment before a variable is used

frigid sequoia
#

Gotcha

swift crag
#

so fields are just initialized automatically to cut down on pointless initializers

#

that's my interpretation, at least

night adder
#

Is it possible to swap a CapsuleCollider2D between horizontal and vertical with a script?

frosty hound
#

Sure, if it's a property on the component, you can change it in script.

solemn summit
night adder
#

Preciate it fellas

long lantern
#

Anychance anyone know how to fix this

timber tide
#

maybe

long lantern
#

How

summer stump
#

!code

eternal falconBOT
summer stump
#

!screenshots

eternal falconBOT
#

mad No

Be mindful, if someone requests your code as text, don't send a screenshot!

teal viper
timber tide
#

read your errors

summer stump
#

@long lantern
using Random = UnityEngine.Random will resolve the ambiguity if you can't remove System

Otherwise you can qualify the Random by writing UnityEngine.Random.Range

But as you were told before, don't take photos of your screen. That should really go without saying...

swift crag
#

at least wipe off your camera lens

#

you get those streaks when it's got oil on it

long lantern
#

na my camera just ass

frosty hound
#

Well there's ways to not have to use it

small mantle
#

I'm making a shapeshifting system. This system will have both a regular human form and a shapeshift form. However, the shapeshift form will have more than one type, while the human has only one. I want to know a simple way I can check what form the shapeshift is. I was thinking of using bools, but am not sure how in this case or if there is a better variable type to use.

timber tide
#

I'd say make a bool to check if you're shapeshifted, assuming there's much a human form can do that all shapeshift forms can't do, and then considering how many forms you may have, you can always check upon the type, or enum if you want to keep shapeshift as a single class.

#

The OOP way would be design a bunch of method implementations like Jump(), Dash(), ect, that all forms would implement and just call them when you do those specific action regardless of your type. Even if some types could not dash, you'd still call them with a minimal implementation.

burnt rampart
#

Hi, so I found I'm running into a common issue, my script is finding an object that is destroyed on next update. Seen a lot of people with similar issues on stackoverflow, but how do you actually get the findObject to be delayed by one update()? One vaguely mentioned it can be done with a bool?

timber tide
burnt rampart
small mantle
timber tide
#

Well, you can do it two ways. One would be to add a flag or disable the object and check against those flags, or resolve the issue in which your methods do not break if these objects are destroyed in the next frame, such as checking nulls and retargeting as an example.

timber tide
burnt rampart
timber tide
burnt rampart
timber tide
#

Yeah, exactly. Just run the method again if needed, but ideally in the next frame and not in a while

faint osprey
#
                {
                    Destroy(currentHole);
                    yield return new WaitForSeconds(0.5f);
                    Instantiate(hole, PM.dungeonSpawns[Random.Range(0, 9)].transform.position + PM.currentRoom.transform.position, Quaternion.identity);
                    Instantiate(hole, PM.dungeonSpawns[Random.Range(0, 9)].transform.position + PM.currentRoom.transform.position, Quaternion.identity);
                    Instantiate(hole, PM.dungeonSpawns[Random.Range(0, 9)].transform.position + PM.currentRoom.transform.position, Quaternion.identity);
                    Instantiate(hole, PM.dungeonSpawns[Random.Range(0, 9)].transform.position + PM.currentRoom.transform.position, Quaternion.identity);
                    EH.treeSpawnCount -= 1;
                    Destroy(gameObject);
                }``` ok this spawns in some gameobjects at spawnlocations pre set out however it chooses them randomly what i want to do is adter the first gameobject has instantiated i want that spawn to not be able to get chosen in the next instantiate
#

how would i go about doing that

north kiln
#

It's generally easiest if you shuffle the array and then just iterate over it

ivory bobcat
#

Here's a pure c# implementation of creating and randomizing an array

north kiln
#
public static void Shuffle<T>(this IList<T> list, int start = 0)
{
    int count = list.Count;
    for (int i = start; i < count - 1; i++)
    {
        int j = UnityEngine.Random.Range(i, count);
        (list[i], list[j]) = (list[j], list[i]);
    }
}
small mantle
#

It's my first time using . I am trying to make bools with them, is that possible?

small mantle
# ivory bobcat Make bools with what?
void ManageType() {
        if (shapeShiftType.light) {

        }
    }

    public enum shapeShiftType {

        light,
        heavy,
        dark

        }``` This code I want to use similar to a bool.
#

It will check if the type is light, dark, or heavy. <- How can I achieve this?

ivory bobcat
#

Use the compare (==) operator or a switch for enums

small mantle
eternal needle
#

You would compare this to a value, the same way you do already with any other data type like int.

int number = 0;
...
if (number == whatever)

you are missing an object of type shapeShiftType

ivory bobcat
#

== is the equality operator that checks if two things are the same (value/ref)

eternal needle
#

what you're trying to do right now is like
if(0)

ivory bobcat
#

Where it would check whatever is left and right of the equality operator

small mantle
eternal needle
#

i am saying right now you dont have any object of type shapeShiftType. There are just values defined for type shapeShiftType.

ivory bobcat
#

If myLight == shapeShiftType.dark
it was dark

north kiln
#

enums are just named integral types, starting from 0, in your case light = 0, heavy = 1, and dark = 2.
So your if statement if (shapeShiftType.light) { is basically just if(0) {

#

Declare an instance of shapeShiftType so you can set it to any of those values, and compare it against the one you're checking for

small mantle
north kiln
#

That'll do it

eternal needle
#

yes now you can compare that to being light, heavy, dark

small mantle
ivory bobcat
#

Or rather switch (myLight) case shapeShiftType.light: ... break; case shapeShiftType.heavy: ... break; ... etc

north kiln
#

functionally, sure, but they're now named

small mantle
wet heath
#

what's the best way to make an openable/closable door for a very simple 3d game? Using hinge components, an animation, using code, what?

charred spoke
#

Your gonna have to use code for any method

#

With a hinge you would get a more physicsy type of door you can push. Animation would be probably be easier to set up

#

Just one animation for opening and then play it in reverse for closing

small mantle
#

Is there a way to make this easy to change? I know that there isn't a stats variable. I am asking how I can make one that functions like a overall stat ```cs
case 0:
turretStats = LightTurret.stats;
break;
public class LightTurret : TurretStats{

public float hp = regular;
public float dmg = low;
public float moveSpeed = veryFast;
public float jumpForce = strong;

}

charred spoke
#

Is this pseudo code ?

polar acorn
small mantle
polar acorn
polar acorn
# small mantle Correct!

Probably the best way to do this is to create an enum for the different types, and then for each variable instead of having a single float, make it a list or array. Then you can cast the enum to int and use it as an index to the list

#

So "light" is 0, "medium" is 1, "heavy" is 2, etc.

teal viper
#

Maybe a list of predefined SOs for stats?

polar acorn
#

And enums are just integers under the hood, they count up in order. So if you just define them in some order and keep that same order when you write your lists you can use a named enum as an index

#

If you don't want to worry about ordering it, a dictionary is fine too

wet heath
languid spire
wet heath
#

oh nice, tyvm

#

I'll check that out

little garden
#

apparently unity does not support dynamic even in mono ;-;

#
error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'
charred spoke
charred spoke
ruby bane
#

Hello, I'm not sure if this question belongs here as I'm not sure if it involves changing code or not.
I have an avatar ready to be uploaded, but there's one more animation I want to it.
However, when importing the animation file, I get errors and I believe it's saying the scripts for the animations are trying to run from dynamic bones, when the avatar uses physbones. Is there a way to update/change the script so it will use the physbones instead?
Thank you!

north kiln
#

None of this is built-in Unity, it sounds like !vrchat

eternal falconBOT
north kiln
#

uploading an avatar, physbones, dynamic bones... these are all non-standard things

ruby bane
#

Ok, sorry.

wet heath
hybrid tapir
#

how do i adjust the position of a tmp_text

hybrid tapir
#

i was trynna use transform.position lol

nimble scaffold
#

what to put here?

eternal needle
little garden
#

where tf are my log files

#

my log files are created when running in unity editor

#

but if i build then run manually no log files get created

sweet osprey
#

I have a script Script1 that has line "public Script2 script2" inside it (which I drag in the Script2 on script1's inspector to make it work)

and then I have a THIRD class Script3 that has a "public Script1 script1" line inside of it (which I drag in Script1 on script3's inspector), and is trying to do:
script1.script2.score = 1
but the error log says Object reference not set to an instance of the object.

what would you do in Script3 to fix this error? i can post actual code if this is described too confusingly

cunning rapids
little garden
#

ok i got it working

#

turns out i had an uncaught exception

#
[ now : 17:41:8:359] [ since last : 0:0:0:19 ] CAUGHT EXCEPTION while initializing ScriptManager : System.IO.FileNotFoundException: Could not find a part of the path "C:\Users\small\Game Engine Projects\Unity Projects\Flow - Unity 2023\Build\Net21\netstandard.dll".
languid spire
timber tide
charred spoke
timber tide
#

yeah may just wanna use raycasting

#

rigidbody is actually decent at highspeed stuff, but you may need to add some additional logic

#

(at least better than my methods)

prime horizon
#

I'm making the character be able to dash, but when the character in the air, the character dashed really short. I hooked up a Debug.Log to monitor the dashVelocity variable, but it turned out to be identical even when in the mid air.
This is the code handling the Dash methods
https://gdl.space/ajanucicof.cpp

prime horizon
timber tide
#

you only set the velocity once in the script but it's still being changed throughout the coroutine, no?

#

actually not too sure, but log throughout the duration if you havent

faint sluice
zealous atlas
#

how do you fix issues like this with cubemaps?

little garden
#

welp i ran a full release build and dynamic and non-dynamic are both signifigantly faster

        bool use_dynamic = true;
        if (use_dynamic) {
            Debug.Log("obtaining class instance");
            if (instantiate_class(compileInfo, "Main", out var instance)) {
                Debug.Log("obtained class instance");
                dynamic i = instance.instance;
                actionQueue.Enqueue(() => i.onStart(obj, 1));
                actionQueue.Enqueue(() => i.onStart(obj, 2));
                actionQueue.Enqueue(() => i.onStart2(obj, 3));
                actionQueue.Enqueue(() => i.onStart2(obj, 4));
            } else {
                Debug.Log("failed to obtain class instance");
            }
        } else {
            {
                if (sm.obtain_callback_direct<Runnable<GameObject, int>>(out var del)) {
                    actionQueue.Enqueue(() => del(compileInfo, "Main", "onStart", obj, 1));
                    actionQueue.Enqueue(() => del(compileInfo, "Main", "onStart", obj, 2));
                    actionQueue.Enqueue(() => del(compileInfo, "Main", "onStart", obj, 3));
                    actionQueue.Enqueue(() => del(compileInfo, "Main", "onStart", obj, 4));
                }
            }
        }
#

compared to just running it in the Unity Editor

teal viper
faint sluice
zealous atlas
#

```cpp
 int2 pixelCoord = int2(id.xy);
    float2 uv = float2(pixelCoord)/cubemap_res;

    float PI = 3.1415926535;

    float3 position = calcPosition(uv, tbn);
    float2 long_lat = longlat(position);
    float2 sampleUv = float2(
        (long_lat.x + PI) / (2.0 * PI),
        (long_lat.y + PI / 2.0) / PI
    );

    float radius = cos(abs(long_lat.y));
    float distortion = 1.0 / max(radius, 0.0001); // Avoid division by zero
    float level = log2(distortion);

    float lowlevel = floor(level+1.0);
    float local = fract(level);

    float3 color = (textureLod(equirectTexture, sampleUv, level).xyz)*(1.0-local)
    +(textureLod(equirectTexture, sampleUv, lowlevel).xyz*local);

that's my calculation to make up for the stretching but that does not seem to be working, why is that so?

prime horizon
# faint sluice Debug all the way xD

That's the worse part of it, I might say. I really don't know how to utilize the debug feature :))
Everytime I look at the debug, my brain cooks itself and die :))

faint sluice
prime horizon
faint sluice
prime horizon
zealous atlas
#

how do you get rid of distortion in a cubemap?

west sonnet
#

My animation only plays once. Anyone know why that could be? My code for the animation is pretty simple

sonic dome
#

click the animation in asset

#

there will be a loop check

#

make sure its checked

#

@west sonnet

honest haven
#

doesnt seem to toggle and is constainly on. not sure if thats the correct componenet

zealous atlas
#

how can I fix my cubemap looking like this that' s the map I'm unwrapping onto my cubemap

gilded verge
languid spire
#

@zealous atlas @gilded verge This is a code channel

zealous atlas
#

it's a math issue

timber tide
#

well, take it to advance with some actual math then instead of assuming we know it by the image

gilded verge
languid spire
neon fractal
rancid tinsel
#

@slender nymph that issue is had with OnMouseEnter/Exit fixed itself randomly just when i was about to ask my lecturer about it :/

#

Didn't change anything at all and it just started working properly

slender nymph
#

could've just been an editor bug đŸ€·â€â™‚ïž

rancid tinsel
#

Kind of upset that I can't find out what the issue was but I guess its better that it's fixed

#

I rebuilt the project on a new unity version as well which works fine so it was all a waste of my time 😭

#

I did learn how to use pointerevents tho so thats good

pale jetty
#

hi, i wanted to knwo why i can't drop the TMP Text i created in the slot of the function (it even says that the type is mismatch, anyone knwo why?)

#
public class InventorItem : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler,IPointerDownHandler,IPointerUpHandler
{
    // item Trashable
    public bool isTrashable;

    //Item Info UI
    private GameObject itemInfoUI;

    public TextMeshProUGUI itemInfoUI_itemName;
    public TextMeshProUGUI itemInfoUI_itemDescription;
    public TextMeshProUGUI itemInfoUI_itemFonctionaliter;

    public string thisName, thisDescription, thisFonctionaliter;

    //Consommer
    private GameObject itemPendingConsumption;
    public bool isConsumable;

    public float healthEffect;
    public float caloryEffect;
    public float HydratationEffect;

    // Start is called before the first frame update
    void Start()
    {
        itemInfoUI = InventorySystem.Instance.ItemInfoUI;
        itemInfoUI_itemName = itemInfoUI.transform.Find("ItemName").transform.Find("Nom").GetComponent<TextMeshProUGUI>();
        itemInfoUI_itemDescription = itemInfoUI.transform.Find("ItemDescription").transform.Find("Description").GetComponent<TextMeshProUGUI>();
        itemInfoUI_itemFonctionaliter = itemInfoUI.transform.Find("ItemFonctionaliter").transform.Find("Fonctionaliter").GetComponent<TextMeshProUGUI>();
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        itemInfoUI.SetActive(true);
        itemInfoUI_itemName.text = thisName;
        itemInfoUI_itemDescription.text = thisDescription;
        itemInfoUI_itemFonctionaliter.text = thisFonctionaliter;
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        itemInfoUI.SetActive(false);
    }```
slender nymph
#

are you sure you are using a TextMeshProUGUI object? and if you are certain that is the type of object you are dragging in, are you certain that you are not trying to drag a scene object into a prefab?

queen adder
slender nymph
pale jetty
slender nymph
#

you can literally just look at the component to confirm. but yes that would most likely be a TextMeshProUGUI object

#

so now we move on to the second part of my message, are you dragging a scene object into a prefab

pale jetty
#

yes

slender nymph
pale jetty
#

i dragged into prefab asset

zealous atlas
tough lagoon
zealous atlas
#

thanks that makes a lot of sense, so I can't use a eqirectangular texture as a skybox?

faint sluice
zealous atlas
#

llody gave me some crazy good info

#

thanks

tough lagoon
zealous atlas
#

oh so I have to use a different projection?

tough lagoon
#

I think so, I'm just waking up in honesty, so my brains a touch fuzzy... I'm having a hard time finding a good reference for you

#

I know unity out of the box handles a bunch of different projection types. And that they can be used for skyboxes. The bottom image in your example looked like it was more meant for a UV sphere or something therein

#

But the visual looked like it's trying to draw it as a 360, so it squishes the top and bottom

zealous atlas
#

hm yes so following things are happening
I have a equirectangular map
then a shader writes to each face of the cubemap using longitude and latitude but the pixels get dispatched for each pixel on the cubemap

limpid wren
#

I'm putting a lot of projectiles on the screen at once and am looking for a good solution to this. The projectiles can't be replaced by raycasts as they are slower moving objects.

Should I still put a rigidbody on these and move them through its velocity, or is there a better way to do this? The projectiles will have colliders on them and not necessarily always move on a straight line.

limpid wren
#

Maybe like, 20 on screen at once

#

up to maybe 40

languid spire
#

not a lot, use rigidody

limpid wren
#

What do you consider the upper limit for rigidbody to be?

timber tide
#

it also depends how fast they are going

#

test it out first with rb though

languid spire
limpid wren
#

I do need a rigidbody on objects that are supposed to physically collide, right?

#

As opposed to just registering "hits"

buoyant knot
#

only if they move

languid spire
#

you need a rigidbody on one or both of the collidee and collidor

tulip stag
#

Why am I getting a null reference exception in ``` private void MoveToCursor()
{
// Trace a ray from the camera to the mouse position
mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
bool hasHit = Physics.Raycast(mouseRay, out hit);

    // Move to the mouse position
    if (hasHit)
    {
        agent.SetDestination(hit.point);
    }
}``` in the line with `Camera.main.ScreenPointToRay`? Like, I assume it's because the reference to the `Camera` is null, but shouldn't `Camera.main` automatically be assigned to my `Camera` Game Object?
limpid wren
#

So bullets that bounce off walls for example

#

I could have a rigidbody on the bullet but don't need one for the wall

#

a collider is enough?

languid spire
#

yes, or the other way round

buoyant knot
#

physics system moves things while respecting collidions by moving the rigidbodies during physics step

#

if you have an obj with collider, no rigidbody, and doesn’t move, then it will be fine

limpid wren
tulip stag
tulip stag
timber tide
#

Unity tags if you've not used them yet

tulip stag
#

oh.

limpid wren
tulip stag
#

Thanks guys lmao

buoyant knot
#

i just put a singleton on my main camera for other reasons

tulip stag
timber tide
#

object pools, game managers, level managers

#

vfx managers (basically another object pool), load/save manager

#

databases; items, enemies, npcs (scriptableobject lookup)

buoyant knot
#

i don’t make objects singletons. I make scripts that should be singletons, and put them on objects that should be unique. Because almost every unique object would be getting unique code

tulip stag
buoyant knot
#

like, if i make a CameraController that moves the camera, that should be a singleton

#

i should never have 2 instances fighting over the camera

#

then obviously, CameraController would be on the Camera’s object

#

I also have a singleton called WorldObjectReferences, that just stores serialized fields as references to unique gameobjects that lack code.

#

Things like the starting position and goal flag

timber tide
#

This way you wouldn't have a single camera singleton, but if you grab a player key then you can refer to that specific one. Another type is similar to gameobject component searching where the key reference is composed of different types not known at compile time.

wet heath
queen adder
#

Can any one help, my problem is that i can see trough the wall, i cant pass the wall but i can see trough it, i dont want to see trough the wall.

timber tide
#

mess with the near clipping plane on the camera

charred spoke
thorn holly
wet heath
queen adder
wet heath
#

But that might just be becuz of the character controller?

charred spoke
thorn holly
wet heath
#

Okie doke ty

swift crag
#

either way will work

atomic yew
slender nymph
#

show !code

eternal falconBOT
atomic yew
atomic yew
slender nymph
#

well none of that is code. but have you considered fixing your errors?

atomic yew
slender nymph
#

probably, but i literally have no way of knowing becuse you didn't bother sharing any relevant code. but you should start by fixing the actual errors in your console before attempting to fix any potential logic issues

atomic yew
graceful flame
#

Hey, I am working with wheel colliders to try and get a bike going... I'd say technically... the bike works and drives... but as part of my degree I have a physical bike here which sends data to my game...
In said data there is a km/h (m/s) value - so... I am trying to accelerate the bike to said value... (I don't wanna go into it rn as of to why, I can later though)...

So my problem is... when increasing torque/... the bike only accelerates to about 1.3m/s (and not the 8.3m/s that I am currently trying to test)
Even when increasing the torque to "yes" it stays at around 1.3... maybe gets a bit higher... but I can't accelerate/decelerate in a manner that makes sense... and I am deeply lost...
has anyone maybe an idea what to do? I watched some tutorials and yes read through documentation... but I can't get it running.
Anyone perhaps has a minute to help me?

#

thats the torque I try to apply to the wheel...

#

but it seems to "slip" even when I crank up friction...

slender nymph
#

just lerp the alpha channel on its color to 0 and back to 1

velvet dawn
#

hello

#

how do i control player's terminal speed if i use addforce with forcemode.force

swift crag
#

Terminal velocity is a product of your drag.

#

However, I'm guessing you don't want to have to fine-tune drag to get the exact velocity you want.

slender nymph
#

you can also just clamp the magnitude of your velocity after applying force if you want finer control over the maximum possible velocity

swift crag
#

An alternative is to just reduce the amount of force you apply if it's in the same direction as your velocity

polar acorn
velvet dawn
tight saffron
#

hello im encountering a problem that i am not familliar on my unity. im trying to make a 2D game but when i started to try my code, it isn't working. i already have a terrain and it also have a collider even the character. why is that?

velvet dawn
#

tysm fen

slender nymph
eternal falconBOT
swift crag
#

Vector3.Dot tells you how well aligned two vectors are

#

That’ll be useful

tight saffron
slender nymph
rocky gulch
#

can you not drag a child class script to a parent class list in inspector

slender nymph
#

you can

wintry quarry
tight saffron
rocky gulch
wintry quarry
lavish gate
#

Getting a Kernel at index0 is invalid although there are no errors?

rocky gulch
#

oh ok

#

should i bother with this

#

or do i just ignore it and its done

slender nymph
#

this means you have either dragged in something that is the wrong type or you are trying to drag a scene object into a prefab

wintry quarry
rocky gulch
#

i did what u said XD, i dragged a gameobject filled with the child script to parent list

wintry quarry
#

You should show the code and then show exactly what you dragged and where you dragged it

swift crag
# velvet dawn owo that... could actually work

here's a rough idea:

// cut force by by 0% at slowdownStart and by 100% at maxSpeed
float speedFactor = Mathf.InverseLerp(slowdownStart, maxSpeed, rb.velocity.magnitude);

Vector3 desiredMove = // get this from player input
float alignment = Vector3.Dot(desiredMove.normalized, rb.velocity.normalized); // 1 when aligned, -1 when opposite directions
float alignmentFactor = Mathf.InverseLerp(1, 0, alignment); // 0% when aligned, 100% at 90 degrees or more

float forceMultiplier = Mathf.Lerp(1, alignmentFactor, speedFactor); // as speedFactor rises, we care more and more about which way the plyaer is trying to move
wintry quarry
deep quarry
#

@tight saffron

velvet dawn
#

hey sorry to bother again but by what scale should i reduce force
also i am adding force while i hold the button to make player move ,how exactly is it supposed to work?

swift crag
#

i don't like the variable names

swift crag
rocky gulch
# wintry quarry fix it

i think this is what u wanted? im not sure
i dragged a gameobject with a card child in it towards the database and there's that

tight saffron
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown("escape"))
        {
            GetComponent<Rigidbody2D>().velocity = new Vector3.(0, 14, 0);
        }
    }
}
swift crag
tight saffron
swift crag
rocky gulch
#

hold on

tight saffron
#

the component is already at my character and not on the ground

slender nymph
eternal falconBOT
polar acorn
rocky gulch
#

confusion 1000

swift crag
rocky gulch
#

oh

#

its in the scene

swift crag
#

Assets can't reference scene objects.

slender nymph
rocky gulch
#

my bad

swift crag
#

It's the same reason prefabs can't reference scene objects. Prefabs are assets.

#

Sounds like you want to make that card into a prefab.

#

and then, presumably, use the card database to store all your card prefabs so you can spawn them

rocky gulch
#

yeah xD

#

thanks for the help

rare basin
#

use DoTween

#

you can fade in/out/chain things in seconds

#

DoTween.DoFade(desiredValue, duratin)

slender nymph
#

if you don't understand how if and else statements work i'd recommend going through some basic c# courses like the ones pinned in this channel

rocky gulch
tight saffron
slender nymph
#

screenshot it

cosmic dagger
#

First you check if alpha is greater than or equal to 0. Then the enclosing statement checks if it's equal to 0

Your first statement subtracts alpha if it is equal, so the second if statement won't be true

Also, don't check for equality with a float . . .

tight saffron
slender nymph
#

so you didn't even copy the code correctly then

tight saffron
#

oh i changed it i forgot

slender nymph
#

and pay attention to the console when you try pressing the key

tight saffron
#

thanks ill configure it later

#

ill try to make a progress

rare basin
#

it's a asset

#

from assetstore, it's free

swift crag
# tight saffron thanks ill configure it later

when you use a string with GetKeyDown, the compiler cannot help you if you type the name wrong -- all it cares is that you gave it a string

when use a KeyCode, you must type a correct name from the KeyCode enum, like KeyCode.Escape -- if you use an invalid name, you get a compile error

rare basin
#

then make it work

#

then you did it incorrectly

errant spear
#

Does someone knows how to get rid of that problem?

rich adder
#

do people even read warning/errors anymore..

errant spear
#

That's the error

wintry quarry
#

yes we klnow

#

remove all the broken script things

#

that's all

wintry quarry
errant spear
#

There's nothing linked

#

no script

#

nothing

#

and it displays that

wintry quarry
#

and remove it

errant spear
#

Ok wasn't thinking i can just remove it

queen adder
#

I have a Serializable class named "Stink". When i create without "readonly" keyword, it works fine. But with readonly, i get null exceptions. How can i avoid that?

Works
private Stink stink = new ();

Not works
private readonly Stink stink = new();

wintry quarry
#

Show the code that throws the exception and the full exception

#

actually I think it makes sense. When unity tries to replace your instance with the serialized instance, it won't be able to because you marked it as readonly

#

remove readonly to avoid that.

queen adder
#

hello

wintry quarry
#

you can't make a serialized field readonly, the Unity Engine needs to be able to write to it.

queen adder
#

i have a issue

this is how it seen at first and then it becomes that when i run the game

queen adder
#

character falls and then this happens

wintry quarry
queen adder
#

there is no code right now its only a character rigidbody2D box Colliders and Bones

polar acorn
queen adder
#

oh im sorry

polar acorn
wintry quarry
queen adder
#

when it hits the floor

queen adder
wintry quarry
polar acorn
#

Ah, the "Completed Solitaire" effect, that's what the issue was

#

I didn't even think to check that

queen adder
#

IT WORKED

#

thank you dude

vague dirge
#

Hello, I'm using Input Manager for a project and when I use use it for joysticks, my character is going forward by default as if the joystick was held up, but it's in its neutral position. Does anyone know how to fix it ?

ashen coral
#

Hello guys, can you help me with this. I don't know where the error could be. The list (screenshot 1) should include "PlayGame0" and "QuitGame 0", but they are not there. screenshot 2 - code (making a menu for the game)

slender nymph
#

you need to fix your compile errors and get your !IDE configured 👇

eternal falconBOT
proper flax
#

can somebody tell me why this isnt working for the movement

eternal falconBOT
#
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

‱ Visual Studio (Installed via Unity Hub)
‱ Visual Studio (Installed manually)

hexed terrace
#

Fix your VS first

earnest atlas
#

_movevector always 0y 0x.

void Awake()
{
    _rb = gameObject.GetComponent<Rigidbody>();
    _controls = new PlayerControls();
}
void OnEnable()
{
    _controls.Enable();
    _controls.PlayerControl.Movement.performed += OnMovementPerformed;
    _controls.PlayerControl.Movement.canceled += OnMovementCancelled;
}
private void OnMovementPerformed(InputAction.CallbackContext context)
{
    _moveVector = context.ReadValue<Vector2>();
    
}

Also for some reason cant see serialized fields in editor?
[SerializeField] private const float PlayerSpeed = 5f;
[SerializeField] private const float UpwardForce = 10f;

#

Im using unity input system

hexed terrace
#

I would say you can't see those fields because they're const .. but I haven't tried that before, I'm assuming

slender nymph
#

yeah const wouldn't be serialized because they cannot change at runtime

earnest atlas
#

Yeah changed that now I can

#

But why input sistem not working?

#

I did it how person in the guide did but my vector is always 0.0

hexed terrace
#

if it works for them, but not you, you did not do it how they did - you've missed something or done something wrong

slender nymph
slender nymph
#

what didn't help? fixing your compile errors? because that will fix the issue

earnest atlas
#

Im determining it with debug LogWarning

#

Thats just showing me move Vector

#

On left is guide, on right is mine

slender nymph
#

again, show the full !code

eternal falconBOT
earnest atlas
#
public class PlayerController : MonoBehaviour
{
    [SerializeField] private float PlayerSpeed = 5f;
    [SerializeField] private float UpwardForce = 10f;

    private Rigidbody _rb;
    private Vector2 _moveVector = Vector2.zero;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    private PlayerControls _controls;

    void Awake()
    {
        _rb = gameObject.GetComponent<Rigidbody>();
        _controls = new PlayerControls();
    }


    void FixedUpdate()
    {
        if (_moveVector.y > 0) // Checks if movement is up and there is no upward velocity.
        {
            // I wanted jump to feel like jump instead of movement.
            if (Mathf.Abs(_rb.velocity.y) > 0.1f) return;
            _rb.AddForce(Vector3.up * UpwardForce, ForceMode.Impulse);
        }
        else
        {
            var movement = PlayerSpeed * Time.deltaTime * new Vector2(_moveVector.x, _moveVector.y);
            transform.Translate(movement, Space.Self);
        }
        Debug.LogWarning($"Movement: {_moveVector.y} {_moveVector.x}");
    }

    void OnEnable()
    {
        _controls.Enable();
        _controls.PlayerControl.Movement.performed += OnMovementPerformed;
        _controls.PlayerControl.Movement.canceled += OnMovementCancelled;
    }

    void OnDisable()
    {
        _controls.PlayerControl.Movement.performed -= OnMovementPerformed;
        _controls.PlayerControl.Movement.canceled -= OnMovementCancelled;
        _controls.Disable();
    }

    private void OnMovementPerformed(InputAction.CallbackContext context)
    {
        _moveVector = context.ReadValue<Vector2>();
        
    }

    private void OnMovementCancelled(InputAction.CallbackContext context)
    {
        _moveVector = Vector2.zero;
    }
    /**/
}```
hexed terrace
#

oof

#

!code

eternal falconBOT
earnest atlas
#

I mean its the same as that guide had almost

#

I dont get any errors in console

hexed terrace
#

You also have to setup the actions assets (or whatever they're called) correctly

earnest atlas
#

I had provided their screenshot

#

They at least look the same as on guide one

slender nymph
#

why do you have a hold interaction on your Movement action

earnest atlas
#

They added on default

slender nymph
#

try removing it

#

because with it you have to hold the input for whatever the duration is set to for it to invoke the performed event

earnest atlas
#

Nope still 0,0

#

I did everything like in guide and its just not working

green copper
#

I'm trying to follow a tutorial for grid based inventory but using touch controls instead of mouse. No matter where I place the anchor for the grid, the code always treats the center of the coordinate system as the bottom-right corner of the screen.

slender nymph
earnest atlas
#

you mean this?

slender nymph
#

no, i mean the setting that is literally called Active Input Handling in the Player settings

earnest atlas
#

I dont get it

proper flax
#

can someone please tell me whats wrong

#

its movement

slender nymph
eternal falconBOT
proper flax
#

i just updated it

slender nymph
slender nymph
hexed terrace
earnest atlas
slender nymph
earnest atlas
#

Why in the guide nothing was told about this

slender nymph
#

how should i know? but the option to enable the input system was given to you immediately after you installed the package

earnest atlas
#

Huh, dont remember. Probably missed it.

slender nymph
#

you can't miss it. it's a pop up window that prevents you from doing anything else until you've clicked yes or no on it

earnest atlas
#

I was at same time looking into the guide when it was installing

slender nymph
#

what guide? the video you screenshot before?

earnest atlas
#

Yeah the Unity Input

slender nymph
#

link the video

earnest atlas
#

https://www.youtube.com/watch?v=UyUogO2DvwY&t=509s
Its one of shorter ones, not like long ones dont waste 80% of time setting inputs for everything

In this video I walk through step by step on how to move a simple 2D sprite using WASD, Arrow Keys and the Left Analogue of a controller.

Starting Project GitHub: https://github.com/LMutlow/YT_Input_Tutorial

I'm still new to making these tutorials so please leave any feedback or ideas for future videos in the comments section below!

▶ Play video
slender nymph
#

1:09

earnest atlas
#

Dont remember this happening

polar acorn
minor vale
#

Just start over

earnest atlas
#

What cycle who?

#

gtg

green copper
#

Despite the inclusion of the RectTransform difference in the code, the origin of the grid is always the bottom right corner of the screen. This persists if the anchor is set to the top right, as well.

slender nymph
#

get its anchored position not its position

#

also you don't need to use GetComponent<RectTransform> you already have a reference to the transform, just cast it to RectTransform instead

green copper
#

Is this a relatively recent change? The guide I'm following is two years old and didn't mention it

slender nymph
#

no, it's how you've always had to get the anchored position of the object

green copper
#

Odd... maybe I just missed it, but thank you for the help

#

seems to be working now

craggy oxide
#

this script works. but i want to replace Input.GetKeyDown("a") with Input.GetAxis("Horizontal")
problem is, Input.GetAxis counts as a float not a boolean so it doesn't work with the If statement
is there any way of making this happen?

slender nymph
#

compare it against 0

craggy oxide
#

does it automatically gain a higher value than 0 when activated or do i have to assign it that value

slender nymph
#

Input.GetAxis will return a value from -1 to 1 depending on what is held for that axis. when nothing is held it will be 0

#

although GetAxis has some input smoothing so you may want to use GetAxisRaw instead

craggy oxide
#

does anything else need to be changed for GetAxisRaw or can I treat it the same as GetAxis

slender nymph
#

why don't you take a look at the docs and see what the difference is

craggy oxide
#

hey what's the operator for "does not equal"

#

is it !=

slender nymph
#

there are beginner c# courses pinned in this channel, perhaps you should start there

craggy oxide
#

alr well i figured it out

craggy oxide
craggy oxide
#

i feel like checking the documentation and taking courses would have just wasted time lmao

slender nymph
craggy oxide
#

yeah but I mean like, I was just double-checking yknow

#

you didnt need to act like i was completely wrong and clueless if i hit the nail on the head

#

kinda misleading

polar acorn
craggy oxide
#

i spent 30 seconds changing the code to see if it worked, it did, and then i went back to the unity course i'm following

polar acorn
craggy oxide
#

point is, isn't this chat supposed to help beginners instead of just directing them elsewhere

craggy oxide
#

ah

#

yeah you know what thats on me then, fair enough

#

didn't see that lmao

#

my baddd

polar acorn
craggy oxide
#

its over bro

#

its over

atomic yew
slender nymph
#

you can just share your issue and relevant code and errors in here and anyone who knows how to help you can do so

atomic yew
terse yacht
#

i googled how to use the Material.SetColor() and idk what context i have to use it in is it the public void or is it within a public void i just dont understand how to use it i need to use it for my assignment to make it change the color of an object when i apply it to my ray cast it needs to toggle for said color back to default or reset back to default

polar acorn
#

public void doesn't mean anything, that's an accesss modifier and a return value so I have no idea what you mean by that

stark flint
#

hey guys so how do i check if an object is facing another specific object

terse yacht
polar acorn
#

I have no idea what language this is in or what the issue is but general takeaways just glancing at it:

  1. When you find yourself numbering variables, you probably want to use a list
  2. When you're doing the exact same code with the exception of what variables it's affecting, you should use a loop
polar acorn
slender nymph
#

yeah i'm not gonna be able to parse that. i don't read whatever language it is you code in đŸ€·â€â™‚ïž

vague dirge
#

Hello, how can I make my character speed vary from joytick tilt ? I have a vector3 made up from vertical and horizontal values, I tried to multiply it by the sum the horizontal and vertical values, but it doesn't work because it's slowed down diagonally

atomic yew
slender nymph
stark flint
polar acorn
# stark flint please may someone help.

Get the direction from one object to the other, then use the Dot Product of that direction and the object's transform.forward. Dot Product is closer to 1 the closer the vectors are to the same direction. You can check if the value is greater than some amount, and adjust that amount for how much "sameness" you want to check for

#

Try different values to see which one is close enough to what you're expecting

vague dirge
slender nymph
#

show your actual code for how you get input

vague dirge
#

thats it

slender nymph
#

no it isn't. show the full !code

eternal falconBOT
stark flint
#

Sorry i am creating a enemy who walks towards the player rn but everytime the enemy starts walking it then suddenly stops for 10 seconds then continues ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CowboyAnimationScript : MonoBehaviour
{
// Start is called before the first frame update

public Animator cowboyAnim;
public Transform lookObject;
public float maxTurnSpeed = 50f;

private void Awake() {
    cowboyAnim = GetComponent<Animator>();       
 }

void Start()
{
    
}
private void Update() {
    Vector3 direction = lookObject.position - transform.position;
    transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(direction), maxTurnSpeed * Time.deltaTime);
    cowboyAnim.SetBool("walk", true);
    
}

}

polar acorn
vague dirge
#

OH YES THATS IT

#

I FORGOT A MATH.ABS

#

THANK YOU

polar acorn
atomic yew
slender nymph
#

and again, i don't read turkish. i cannot read your code. therefore i cannot help you

terse yacht
polar acorn
buoyant knot
#

i think he/she just does not understand the syntax for C#

polar acorn
#

Exactly, which is why I said to look at the pins

#

Specifically the intro to C# course linked

terse yacht
#

well it was more the fact the website didnt explain what it was it said what it was not how to use or a good example i understand syntax i was getting pissed i could not figure it out that i tried it to see if it would work

stark flint
polar acorn
proper flax
polar acorn
slender nymph
terse yacht
#

thats what i was using i was confused cause ive never use any set color or color related code before

polar acorn
#

with the parameters you want to use

stark flint
polar acorn
stark flint
#

it is however it is taking pauses inbetween

terse yacht
#

so this code is going to be apply to my ray cast interact script i attach it to ray cast and set the toggle and im able to click e for it to change color is the end goal so that means i can change any object color that has my interactable script to it so when unity documentation site say cubeRenderer.material.SetColor dose cube renderer mean just strictly cubes or what cause i assumed i could use mesh renderer cause i have that on all my game objects and apparently i cant use mesh renderer to replace it so what do i have to do?

slender nymph
#

where have you declared the variable called meshRenderer

polar acorn
stark flint
#

even though before the code it just kept the animation going

scarlet skiff
#

why cant i drag my image into the "source image" of the image component??

rich adder
#

also not a code question

scarlet skiff
#

its a png image what else does it have to be

rich adder
#

right now its just a texture according to unity

#

png != sprite

polar acorn
#

in the import settings

#

which is not code

scarlet skiff
#

ok thanks

terse yacht
polar acorn
#

Do you have a variable named meshRenderer in your code

#

What are you trying to get the material of

terse yacht
#

yes but i 100% sure i called it wrong and the end goal is so when i apply it to my interactable ray cast i can look at a said object (any object in my game) and tap my interact button it will switch the color to any color and i was told i have to use material.SetColor to do so

polar acorn
#

Seriously, stop guessing

#

learn C#

slender nymph
terse yacht
meager steeple
#

just a quick question do you have to use visual studio for unity?

slender nymph
scarlet skiff
slender nymph
terse yacht
polar acorn
rich adder
scarlet skiff
polar acorn
meager steeple
#

or is it more personal preference?

scarlet skiff
rich adder
slender nymph
scarlet skiff
#

the texture type

#

it no no wanna

polar acorn
#

you'll need to extract it

rich adder
#

ahh yea its read only

terse yacht
rich adder
#

make a copy is usually fix too

scarlet skiff
#

idk bro i just right cliekd my sprite folder and clicked import new asset

scarlet skiff
polar acorn
#

You are able to learn things outside of a school environment you know. If the class isn't teaching you, there are myriad resources available to learn on your own

#

like the ones in the pins I keep referring to