#💻┃code-beginner

1 messages · Page 121 of 1

rich adder
#

its a basic google serch 🤷‍♂️

#

Unity learn UI

wild cargo
#

Fair

fluid kiln
#

this kinda is a headache ngl cuz its a very specific case, like for the ui i need to use images, and for the game i need to use sprites.

shrewd swift
#

hey
do you guys put all your class vars together ? or do you split between the ones that are shown in the inspector and the ones that arent ?

rich adder
rich adder
#

when i can..

shrewd swift
rich adder
#

nothing is public, only properties and some methods

rich adder
shrewd swift
#

yeah same, but im wondering if im not losing time by making two diff blocks for the inspector

shrewd swift
lethal depot
rich adder
#

forgot about the inspector, thats just the editor

#

whats more important is how clean code is (and functional duh)

rich adder
#

and Center should not be selected, should be Pivot

#

pretty sure your Enemy is turning correctly

#

everything else as child is just parented to wrong forward

#

guaranteed xD

lethal depot
#
namespace GDL_Tutorial
{
    public class EnemyShooter : MonoBehaviour
    {

        [Header("General")]
        public Transform shootPoint;
        public Transform gunPoint;
        public LayerMask layermask;


        [Header("Gun")]
        public Vector3 spread = new Vector3(0.06f, 0.06f, 0.06f);
        public TrailRenderer bulletTrail;
        private EnemyReferences enemyReferences;

        
        void Start()
        {

        }

       
        void Update()
        {

        }

        public void Shoot()
        {
            Vector3 direction = GetDirection();
            if(Physics.Raycast(shootPoint.position,direction,out RaycastHit hit,float.MaxValue,layermask))
            {
                Debug.DrawLine(shootPoint.position, shootPoint.position + direction * 10, Color.red, 1f);

             TrailRenderer trail=Instantiate(bulletTrail,gunPoint.position,Quaternion.identity);
                StartCoroutine(SpawnTrail(trail, hit));
            }
        }

        private Vector3 GetDirection()
        {
            Vector3 direction = transform.forward;
            direction+=new Vector3(
                            Random.Range(-spread.x,spread.x),
                            Random.Range(-spread.y,spread.y),
                            Random.Range(-spread.z,spread.z));
            direction.Normalize();
            return direction;
        }

        private IEnumerator SpawnTrail(TrailRenderer trail,RaycastHit hit)
        {
            float time = 0;
            Vector3 startPosition = trail.transform.position;
            while(time<0f)
            {
                trail.transform.position=Vector3.Lerp(startPosition,hit.point,time);
                time+=Time.deltaTime/trail.time;

                yield return null;
            }
            trail.transform.position = hit.point;
            Destroy(trail.gameObject, trail.time);
        }
    }
}
lethal depot
rich adder
#

the correct one

#

In Local Pivot mode

languid spire
lethal depot
#

i was just trying to follow a tutorial , not my fault😫

languid spire
#

yes, your fault for doing so blindly without engaging your brain

lethal depot
#

okay

rich adder
lethal depot
unborn gale
#

Why does this happen Everytime I open a file in unity

rich adder
unborn gale
#

It doesn’t let ke touch anything in unity and the loading doesn’t stop

#

Cam anyone help

vast vessel
#

How do i do multi threading to make performance better?

#

Or is multi threading just a thing that is there on all unity projects

polar acorn
gaunt ice
#

job system

vast vessel
polar acorn
#

Job system is what you would do but if you're posting here chances are your performance issues are not related to threading

#

Try using the profiler and finding out where the problem actually is

vast vessel
#

But my code has a large delay on my cpu

#

Also i use unitys object pooling for bullets and impact effects in my game

polar acorn
gaunt ice
#

then write your own pool

vast vessel
gaunt ice
#

you said it is slow

vast vessel
#

I meant i did that to increase performance

polar acorn
#

Until you profile the game and find out what is slow, you are just guessing. Get some data, and figure out what can be done to fix it from there

vast vessel
#

Can jobs improve it tho?

#

Like, does it help?

polar acorn
gaunt ice
#

first, can your code multithreaded? (moving rb can be multithreaded but modifying BVH/space partitioning not)

vast vessel
polar acorn
gaunt ice
#

bounding volume hierarchy

#

afaik modification of any tree cant be multithreaded (at least it has to lock the whold subtree)

dry tendon
#

!code

eternal falconBOT
dry tendon
#

Hi everyone... https://paste.ofcode.org/32P9EH6DAxdKwKvL9X8Fr4h In that code i have three big methods in the end of the code, and i wanna move them into separated scripts to keep the organizacion of my code... my doubt is if you recommend me to move them into separated classes or into a partial one of the one they are currently in

#

I listen you all

#

🙂

polar acorn
#

If the functions are only ever used in this class then there's no reason to move them anywhere

#

There's a bit of repeated code you could probably extract into a method, like this bit here

#

You do code that looks basically like this but with different code in several places, that could be a function with those text strings as parameters, and you can call that function instead of doing this in multiple places

dry tendon
dry tendon
#

i'll take a look to that

polar acorn
desert elm
#

so, this should find the component "Unit" for each gameobject that has its collider in this list

polar acorn
desert elm
brazen cedar
#

Hellooo

#

How can I make this folk move towards the object facing it?

polar acorn
brazen cedar
desert elm
polar acorn
desert elm
polar acorn
rich adder
brazen cedar
#

I made a script an looked out for the documentation

#

It just become a singularity

rich adder
brazen cedar
#

But I'm not sure how to make it properly

rich adder
#

gpt code

brazen cedar
upper ember
#

!code

eternal falconBOT
brazen cedar
rich adder
#

all you needed was rotate towards 🤷‍♂️

brazen cedar
#

Can you explain me how it works? How would I define the "face" of the object?

rich adder
#

just set your player as target and ur done

#

just make sure the gizmos are correct in Local Pivot mode.

brazen cedar
#

And wouldn't I need to define a facing side for the object?

brazen cedar
#

Thank you

rich adder
desert elm
brazen cedar
upper ember
#
 void Update()
    {
        horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;
        verticalMove = Input.GetAxisRaw("Vertical");
        if (verticalMove == 1)
        {
            jump = true;
        }
    }

    void FixedUpdate()
    {
        controller.Move(horizontalMove * Time.fixedDeltaTime, false, jump);
        jump = false;
    }
 void Update()
    {
        horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;

        if (Input.GetButtonDown("Jump"))
        {
            jump = true;
        }
        if (Input.GetButtonDown("Crouch"))
        {
            crouch = true;
        }else if (Input.GetButtonUp("Crouch"))
        {
            crouch = false;
        }
    }

    void FixedUpdate()
    {
        //move the Character
        controller.Move(horizontalMove * Time.fixedDeltaTime, crouch, jump);
        jump = false;
        

    }

Following a tutorial and I want to get the jumping and crouching working on just the left analogue stick (trying to learn so it's applicable to fighting games) instead of buttons. For some reason when I try to use the y axis for jumping it sends me to space vs when I use the button jump it's fine (I'm using the Character Controller 2D script from the video, there is no double jump so it's not repeating the jump call when in the air)

#

Also using the dpad would be nice but one step at a time

desert elm
polar acorn
desert elm
#

right need to figure out what that is

polar acorn
desert elm
polar acorn
#

You should probably familiarize yourself with the basic terminology of C# before attempting to make anything in it

upper ember
# upper ember ```cs void Update() { horizontalMove = Input.GetAxisRaw("Horizontal...

Have tried
Adding verticalMove = 0; underneath setting jump back to false (slightly better but still go to space without the fastest of taps on up)
adding jump = false; right after setting it to true in the if statement (no jump)
Using verticalMove >= 0 in the if statement (make problem worse)
Am also using a controller with a digital joystick so that the value should always be -1 / 0 / 1

tender breach
waxen oracle
#

What is a cinemachine camera? Im trying to learn how to transition between cameras and every tutorial says cinemachine

polar acorn
#

You are getting a random number between 0 and the length of your array. That's not a color

tender breach
#

How do I fix it via code?

polar acorn
slender nymph
polar acorn
rich adder
#

Ah okk

short hazel
#

The random number you get is in range of your list, now access said list with that number to get an element

tender breach
slender nymph
#

wow, i'm surprised it is actually configured with that horrible formatting

tender breach
#

Yeah

thorn holly
#
try
{
  triangles.Add(pyramidFormation[l][i].GetComponent<NodeBehavior>().index);
  triangles.Add(pyramidFormation[l + 1][i].GetComponent<NodeBehavior>().index);
  triangles.Add(pyramidFormation[l + 1][i+1].GetComponent<NodeBehavior>().index);
} catch (Exception e) {
  Debug.Log(e);
}

So I have this fairly simple code here, lmk if i have to show more code here, but im logging an error that Object reference is not set to instance of an object. I'm not too sure what I did wrong, again, lmk if i need to show more code

rich adder
#

which is the Color

tender breach
#

And how do I do that?

polar acorn
short hazel
rich adder
slender nymph
#

oh i know, i've seen their war crimes

polar acorn
tender breach
#

I think so.

polar acorn
thorn holly
polar acorn
polar acorn
upper ember
tender breach
#

Look at the code.

polar acorn
thorn holly
tender breach
polar acorn
polar acorn
#

This is the same code

tender breach
rich adder
#

great you got the random Index, but where is the array element?

polar acorn
thorn holly
slender nymph
tender breach
polar acorn
polar acorn
brazen cedar
rich adder
#

Your model however, is not

jaunty lily
#

does anyone have idea if its possible/hard to make a way, that the player is being recorded from a perspective while playing, the whole time? and that that video gets saved somewhere and can be shown at a given time? sorry if im unclear, im new

brazen cedar
rich adder
#

In Unity the Blue is forward

rich adder
#

the code is working tho

brazen cedar
#

Just like that?

#

I will try

languid spire
rich adder
#

also Don't use Center mode for pivot, use Pivot

#

you don't want weird issues later

thorn holly
brazen cedar
polar acorn
thorn holly
#

heres the code that sets it:

NodeBehavior currentNode = pyramidFormation[l][i];
currentNode = nodes[nextAvailableNode].GetComponent<NodeBehavior>();
#

currentNode is a reference to pyramidFormation[l][i]

polar acorn
#

This is one of the reasons you should be using that as your type for all these lists

#

It won't be possible to put something in the list that doesn't have a NodeBehavior

thorn holly
languid spire
polar acorn
#

Ah, right, that too

brazen cedar
languid spire
polar acorn
brazen cedar
#

Should I put all the logic in the father or ir in the same capy?

jaunty lily
rich adder
brazen cedar
#

Since it's still facing wrong

languid spire
tawny rain
#

i keep getting this error when trying to run game what should i do?

jaunty lily
slender nymph
eternal falconBOT
polar acorn
languid spire
short hazel
upper ember
polar acorn
#

You're still calling GetComponentInParent on this object

copper locust
polar acorn
#

Also there's nothing in your foreach loop you end it before you open the curly braces

languid spire
jaunty lily
jaunty lily
languid spire
polar acorn
upper ember
desert elm
polar acorn
#

call the function on that

languid spire
jaunty lily
sand veldt
#

Can anyone guide me for animation on a character
My character has more than one walking style

#

so how can i set it to one random style when it spawn

jaunty lily
desert elm
polar acorn
#

that's what you're looping over

#

Use that

short hazel
# jaunty lily what do you mean?

The thing you record is stored in memory until you write it to a file for example. If you do nothing with it, it will accumulate, fill up your RAM, and your game will crash because it will be out of memory at some point

languid spire
desert elm
#

I am aware now

desert elm
#

if it gets the gameobjects that makes my life easier

jaunty lily
polar acorn
#

Colliders are on game objects

#

Components all have access to all of the GetComponent methods

desert elm
#

oh okay

#

that clears things up, thanks

#

got confused by the wording, as I thought I needed to get the gameobject that the collider is on, and then get components from that

short hazel
jaunty lily
short hazel
jaunty lily
desert elm
#

whats this otherComponent supposed to be?
both of these are wrong

slender nymph
#

look at the warning on your foreach line

desert elm
slender nymph
desert elm
#

oh i see the problem

polar acorn
#

Right now your foreach loop is empty

desert elm
#

yep it works now

#

fucking typos

lavish terrace
#

is there a place to explore what custom codes can add to the inspector ?

#

like variables and stuff

#

seen a vid which added those

#

made me think what else is there to add

lavish terrace
#

ty

dim stream
#

Hi, i have a little problem, i am making my first 2d plataform. I created a dead zone for when you fall, the deadzone works but it works only if you touch it for the side, if you fall in it you dont die and idk how to fix it. Here is the code of the DeadZone:

next jay
#

how could i put a delay between lower and raise to prevent both happening at one click

dim stream
next jay
#

yeah

dim stream
#

i cant help u im very new here

next jay
#

Ok

short hazel
#

Modifying the transform.position directly does not use physics for example

short hazel
#

Then there's a collision, it's just not tagged properly

#

So it doesn't pass the if statement, and Die() is not executed

dim stream
#

that´s the problem because is tagged correctly

#

and if you touch it form the side works

#

an the box is very thick

short hazel
#

Make sure by logging what you hit

dim stream
short hazel
#

Debug.Log($"Hit object {collision.gameObject.name} tagged {collision.gameObject.tag}")

#

Then check the console when the player hits the object, and make sure it's correct

dim stream
#

okey

short hazel
#

Whenever you collide, so in your OnCollisionEnter2D

lost abyss
#

hey, i'm trying to create a replica of flappy bird, but for some reason the bird object auto rotates while playing. Anyone knows what I can do to fix that? It's the Z rotation that does that

dim stream
short hazel
#

It always collided, because your player was standing in the air

#

It's the if statement that didn't pass, making it seem like it wasn't doing anything

#

Just make sure that in the console it says that it collided with an object that has the correct tag

dim stream
#

its correct

tender breach
#

I fixed my problem for now

short hazel
# dim stream

It logs twice, is the script on another object by accident?
From what I see it's meant to be attached to the player only

dim stream
#

im going to check

next jay
dim stream
short hazel
#

Put another log, but this time inside the Die() method. So you can see if it gets executed

open vine
#

Hey, so I have a script where I reference the Weapon : scriptableobject class. I thought this meant that any class inheriting from Weapon should be able to be put into the inspector for a Weapon variable is this wrong?

bleak prism
#

If i have a gameobject saved into a variable what would be the best way to access the child of that gameobject

#

asked the GPT and it said this

short hazel
#

You indeed access parent and children from the .transform

bleak prism
#

So there is no other way to do it?

#

Just to make sure

short hazel
#

There are plenty of ways, and they depend on your use case

#

If you just want a specific child, why not drag the child directly into the slot, for example

#

Like on a variable exposed in the Inspector

bleak prism
#

I could just maybe do that

#

I keep forgeting about the drag & drop

short hazel
#

Debug.Log???

#

Put any message in it, you just want to see if it's getting executed

dim stream
#

a srry i understand another thing

#

wtf

short hazel
#

Are you getting any errors in the console? Make sure you didn't disable them accidentally (3 buttons top right of the Console tab)

dim stream
#

i dont have any error its like the character cant make the transition from fall to death

#

i tried to make a transition directly fall to death

#

but it doesnt work either

#

i am going to re edit the animator i think

rancid musk
#

how should i learn c# there are so many different people telling me different ways to start and its really overwhelming

dim stream
#

idk

#

im new here too

#

i made a beginner unity course

#

but now im using yt tutorials

short hazel
dim stream
grand hare
rancid musk
#

okay

desert elm
#

Right so- I assume this won't work, will it
( second image is in the script of the unit component

slender nymph
#

are you sure you are getting the right kind of Unit component inside that foreach loop? hover over it to see the fully qualified name

shrewd swift
#

~~Camera isn't recognized as a Class in my VS
its not colored like a class and isnt giving me any methods

i tried regenerating VS files but nothing changed~~

slender nymph
#

then there is likely some context you are not showing

shrewd swift
desert elm
slender nymph
#

well for one, it would be great if you stopped sharing screenshots of code

eternal falconBOT
#

mad No

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

golden otter
#

in this coding convention:
Public var: exampleVariable
Private var: _exampleVariable

When serializing a private variable using [SerializeField], should it remain with the underscore in front of it or I should remove it?

slender nymph
#

the convention is about the accessibility, not whether it is serialized or not

slender nymph
hidden sun
#

any idea?

hidden sun
#

i set the project id/envoirment/ my id/pass etccc

slender nymph
polar acorn
#

We could also have seen that if you shared the error

queen adder
#

how to add a permanent contextmenu to all my behaviours? blushie

#
[MenuItem("CONTEXT/MonoBehaviour
```hacky ![UnityChanwow](https://cdn.discordapp.com/emojis/885169594879320064.webp?size=128 "UnityChanwow")
wild cargo
zealous oxide
#

https://hastebin.com/share/qoyuwenilu.csharp hey peeps, im trying to make a conga line of gameobjects to follow a player object, using a public static array for the transforms but the array never seems to work, it never adds in the playerscript.transform as the first item. is a public static array even the right approach for this

#

theres very little info for me to work off online for this, so i wonder if i need to articulate it differently

wild cargo
#

Because it seems you haven't even initialized the array yet when you call that

slender nymph
#

you never initialize the array

wild cargo
#

Also maybe an array isn't the best choice for something like this that can get dynamically changed.. I'd use a List<>

slender nymph
#

honestly a static list isn't necessary either. when one of the objects that needs to follow another is spawned, just pass it a reference to whichever object it needs to follow. and have whatever is spawning them keep a list of what has been spawned

zealous oxide
#

yeah i could do that but if one of the objects gets destroyed in the middle of the chain, i guess it would have to pass the subsequent object into its place? which is getting ahead of myself ability wise

slender nymph
#

have whatever is spawning them also manage destroying them. then when it goes to destroy one, it also tells whichever is following it to follow whatever the destroyed one was following

zealous oxide
#

ok sweet, will do that

empty yoke
#

Dontdestroyonload game objects wouldn't trigger their start function on a scene change, is that correct?

slender nymph
#

correct, Start only happens a single time in an object's lifetime

empty yoke
#

okay so I'd need some like scene manager to trigger any kind of things on a change cool, thank you thank you!

slender nymph
empty yoke
#

😮 oh man that's amazing

#

thank you for the docs!

unborn gale
#

How do I send code here again?

slender nymph
#

!code

eternal falconBOT
real falcon
#

so I got the door to kind of work how I expected using a hinge. However, once it reaches its limit you can keep pushing it and it gets all like, jittery and weird

#

I want it to basically become rock solid, as solid as level geometry, if you are trying to push it past its limit

unborn gale
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Hanger : MonoBehaviour
{
    public bool hanged;
    private Transform hangerTransform;
    private Animator ani;

    void Start()
    {
        ani = GetComponent<Animator>();  // Ensure correct component retrieval
    }

    void Update()
    {
        if (hanged)  // Use comparison for boolean value
        {
            transform.position = new Vector2(hangerTransform.position.x, hangerTransform.position.y);  // Assign 2D position
        }
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("hanger"))  // Match tag exactly
        {
            if (Input.GetKeyDown(KeyCode.Space))
            {
                hangerTransform = collision.gameObject.transform; 
                hanged = true;
                ani.SetInteger("hanged", 1);  // Use correct method for setting integer parameter
                 // Obtain transform directly
            }
        }
    }
}
#

i dont know why the collision wont work

quasi summit
#

guys how much would it cost to make a game with these features:

Match-Three Puzzle Game:

Blocks:

Shapes: Squares, Circles, Diamonds, Triangles, Hexagons.
Colors: Red, Blue, Green, Yellow, Purple, Cyan.
Special Blocks: Star (wildcard block that matches with any color).
Power-Ups:

Line Bomb: Clears an entire row or column.
Color Bomb: Clears all blocks of the same color it is swapped with.
Lightning Block: Clears all blocks in its row and column.
Super Swap: Allows one move that can swap non-adjacent blocks.
Scenes:

Coral Reef: Bright, underwater-themed tiles with a moving water background.
Enchanted Forest: Green and earthy tiles with animated background featuring subtle creature movements.
Space Nebula: Dark tiles with a starry background, featuring occasional comet animations.
Game Mechanics:

Combos: Matching more than three blocks gives increasing multipliers.
Obstacles: Unmovable blocks or chains that require multiple matches to remove.
Vertical Stage Strategy Game:

Characters:

Basic shapes representing different sea creatures, each with a numeric value.
Colors: Differently colored to represent various power levels (lighter colors for lower levels, darker for higher levels).
Gameplay:

Progression: Each 'eat' increases your character's value.
Strategy: The player can only move up to the next stage by clearing the current one.
Power-Ups:

Shield: Temporarily allows your character to eat an opponent one level higher without getting eaten.
Double Points: The next character eaten doubles in value.
Freeze: The points needed for the next opponent increase are halved.
Environment:

Simple backgrounds that change color or have minimal animation to indicate level changes.

polar acorn
quasi summit
#

How come

polar acorn
# quasi summit How come

If you don't know enough unity to gauge the scope of a game then any complete game is probably too much

quasi summit
#

damn

#

how mcuh would it cost tho

slender nymph
# unborn gale ```cs using System.Collections; using System.Collections.Generic; using UnityEng...

two things, first make sure that OnCollisionEnter2D is being called
second, do not use Input.GetKeyDown inside of OnCollisionEnter. GetKeyDown is only true for the first frame that you press the key which may not even be a physics update frame. OnCollisionEnter2D is also only called on physics updates and also only the first frame the collision happens. So you have to have inhuman timing to match those up. consider checking input using GetKey inside of OnCollisionStay or just flip a bool in OnCollisionEnter/Exit and check input in Update when that bool is true

unborn gale
#

i would do it for ten bucks if I didnt have a project of my own

quasi summit
#

Really

#

can u lmk whenever u dont have a project

polar acorn
quasi summit
#

😭

unborn gale
real falcon
verbal dome
#

People who use the cry emoji often dont want to put any work in themselves, just saying

slender nymph
unborn gale
real falcon
#

I think what is happening with my door is that I have a kinematic body pushing on the hinge joint, and I'm thinking for whatever reason the hinge joint doesn't take priority and wont tell the character controller to stop?

polar acorn
unborn gale
#

only the hanger is

#

istriger

polar acorn
unborn gale
#

ok

#

yes it is the problem

#

what can I do

#

I wantto detect them when they overlap

polar acorn
#

Either make it not a trigger or use the trigger function instead of the collision one

queen adder
#

how to edit heirarchy search bar via code blushie

real falcon
#

is it a technical limitation that you can't make joints have solid limits against a kinematic body

verbal dome
#

And a kinematic body basically has infinite mass when it comes to collisions

tender stag
#

why is it in red but it still works?

real falcon
#

I basically have a player with a character controller and a kinematic rigidbody

#

I want this to be able to push a door open, but not jitter when it hits the limit

#

and just block the player

verbal dome
#

Honestly not sure what the best option here is

#

My rb's are usually not kinematic

real falcon
#

I tried making it not kinematic but unity says I cant

verbal dome
#

Huh? Does it have a mesh collider or something?

real falcon
#

no just a capsule

#

but the level geometry is a mesh

verbal dome
slender nymph
real falcon
#

Non-convex MeshCollider with non-kinematic Rigidbody is no longer supported since Unity 5. If you want to use a non-convex mesh either make the Rigidbody kinematic or remove the Rigidbody component.

tender stag
verbal dome
verbal dome
slender nymph
tender stag
#

i updated the visual studio code editor

#

and it works

#

in package manager

#

wait no it doesnt

tender stag
#

everything else works

slender nymph
#

yes and you recently added this asset so vs code does not recognize it. so regenerate the project files for vs code

real falcon
real falcon
#

lol when I make the RB Non kinematic it makes the player fly around like crazy

slender nymph
verbal dome
real falcon
#

I don't want to make the players movement based on physics because of case in point, how finnicky and glitchy physics sims in games always are

#

maybe I should just make the door not really use the physics engine

verbal dome
verbal dome
#

Way easier

real falcon
real falcon
# verbal dome That is easier yes

how do I tell when the player touches it tho, and from what angle? and how does it stop when it touches the player, if the players controller stops it before it even penetrates?

verbal dome
real falcon
#

I remember now that the reason I went to a non kinematic door was because the door would push the player, which would cause depenetration that was jittery

verbal dome
real falcon
#

even if it doesnt end up moving the player?

verbal dome
#

I dont remember all the limitations of kinematic

real falcon
#

should this new door even have a rigidbody?

tender stag
#

disable the collider on the door when its opening/closing

real falcon
#

well, I don't want it to go through the player either

verbal dome
#

Thats how a lot of games do it yes

real falcon
#

the door I'm looking at as an example is from Portal 1, I remember there being a door that you can open and it swings open, but if you try to close it on yourself it just stops as soon as it touches you

#

and it doens't cause any jittering or anything like that

#

OnCollisionEnter only works if one of the ojects has a non kinematic rigidbody

#

which means my door will have to be non kinematic, which means it can bug out

verbal dome
#

Kinematic contact pairs are a thing too. Never used it myself tho

real falcon
#

I want something that blocks the player without depenetration or jittering, but is also blocked by the player in the same way

tender stag
slender nymph
tender stag
#

this is what im trying to access

tender stag
#

not code

#

same thing

real falcon
#

it acts as pure terrain towards the player, and can only move if it's not touching the player whatsoever

lavish magnet
#

It definitely did help, im figuring it out, and the animator overrider controller would go on tbe player? And i wouldvhave one for eavh gun? Eg dif reload animations.? But thats confusing, dude im sorry but do you think you could hop on call and i could screenshare and shownyoi what i got so we could figure something out, you seem way more knowledgeable abiut this than i am, snd i’ve been stuck on it for like a year, I’m willing to pay even, lmk!

real falcon
#

the OnCollisionEnter event doesnt seem to be triggering even if the door is non kinematic

#

its just not running

#

even when Im physically pushing the door, doesnt show that method runs

#

this is the players rigidbody

#

and the doors

slender nymph
real falcon
#

ah I had collider instead of collision thanks

#

now the question of how to make a door with a rigidbody that the player cannot move at all

#

without settnig it to kinematic

#

nvm just set it to kinematic and enabled kinematic collision detection. It actually works pretty well now, I got it moving but stopping if it touches the player and it does not appear to move the player at all, nor does the player seem to be able to move it at all

#

I get intense lag if I push into it at certain angles but I think that's my own code. I'm worried about coding it rotating in response to collisions but maybe it will be easier than I expect

tender breach
#

How do I change variables across scenes in unity?

unborn gale
#

How Do I remove the light symbol from my game?

north kiln
unborn gale
#

Can’t find it

north kiln
#

why have you sent a screenshot of a component? That's not where you disable gizmos

unborn gale
#

Where then?

north kiln
#

I'd also note that this is not a code question and you should have asked in #💻┃unity-talk

tender breach
north kiln
upbeat river
#

can somebody hop into a call with me and help me figure out something?

vast ivy
upbeat river
#

im trying to make a gun

vast ivy
#

Blender

upbeat river
#

and im trying to also make it emit spark particles when it shoots

#

i have a model and simple shooting (raycasting not projectiles) and reloading

vast ivy
#

Ok so you need an onclick function, have you worked with inputs yet?

upbeat river
#

not really

#

just started with unity and coding

vast ivy
#

Ok I think if u press edit, Inputs, and then find mouse down inputs

upbeat river
#

hmm ill try

#

where is the edit?

vast ivy
#

For the code u will need the name of the type of input you’re getting, for example moving your player vertically takes an input of W, S, or Up arrow, Down arrow. This input is called “Vertical”

#

Should be toward the top left of the editor by file

#

(I’m also pretty new but this is something I know) xD

upbeat river
#

i dont see inputs but thanks for the help anyways

vast ivy
#

Ok it’s actually in ur project settings tab but here’s the type of code you’ll want:


void Update() 
{ 
    if (Input.GetKeyDown(KeyCode.Space)) 
    { 
        // Spacebar was pressed 
    } 
        if (Input.GetMouseButtonDown(0)) 
    { 
        // Left mouse was pressed 
    } 
}
#

The update function is in every script by default, it runs every frame. “GetMouseButtonDown(0)” being a left click on mouse

#

In the if statement is where you would put functionality of your gun

#

For the reload u would use the “GetKeyDown(KeyCode.R)”

fierce shuttle
# lavish magnet It definitely did help, im figuring it out, and the animator overrider controlle...

It would go on the object with your Animator component, so say you had a "pistol reload" and a "rifle reload", you could name the state for both to just "reload", and maybe you start with a pistol, so your default "reload" state in your animator controller could be your "pistol reload", when you swap to your rifle, you can then set the entire animator controller to your "rifle override animator controller", which will replace your "reload" from "pistol reload" to "rifle reload" - so in a way, youd need an animation for every gun that is different (for example if you have 4 different types of rifles, some may reload differently than others, while all the different pistols in your game probably reload the same way and can reuse the same animation) - I wont really be able to do a call or anything until after celebrations here, though if you have other questions, I can try to help, otherwise if your willing to wait about a week, I guess we could discuss it in DM

tawdry mirage
#

how to instantiate empty gameObject from code without any reference?

#

i only need it's Transform while it is on the scene

summer stump
#

Or even new GameObject()
Actually, no blank instantiate. I thought there was

tawdry mirage
#

only instantiating components outside of gameObject cause leaks?

tawdry mirage
#

new Transform()

#

i read it somewhere

summer stump
#

Do you know what a memory leak is?

tawdry mirage
#

in case of unity not really

summer stump
#

Do new GameObject()
It will not create a memory leak unless you do something VERY weird.

#

You also can't instantiate components outside a GameObject

real falcon
#

so i have a door that opens if you touch it, the problem is it also opens if you touch it from the wrong side. I'm wondering if there's an easy way to detect if a given movement would end up intersecting an object

#

specifically, this method is what I use to rotate it. is there a way I can like, "preview" it and see if it would collide with anything before I actually move it?

tawdry mirage
#

if it's raycast based you could use one sided mesh collider.
You can also use three colliders setup, two flat trigger-only colliders for each side and one box collider that works with physics but doesn't trigger

tender breach
#

How do I make it so that a collider only detects a single object.

summer stump
real falcon
#

I guess probably it tells you in a parameter

tawdry mirage
#

three gameObjects that are child of parent Door

#

each has to have their own script

real falcon
#

ah

tawdry mirage
#

except one with door box collider

real falcon
#

thats a lot smarter than how I was thinking, thinking i'd have to calculate the direction of the door's motion as a vector and compare it to the direction of the thing you hit etc.

tawdry mirage
#

my solution can cause bugs if you move the touching body at high speeds

#

it can touch both sides if speed is too high

#

hmmm, at high speeds you can go right through the door without colliding with it

steel girder
#

hey, does anyone know how to get the length of an animation for a runtimeAnimatorController/animatorOV's animation?

wintry quarry
steel girder
#

i'm using it for a coroutine

wintry quarry
#

A coroutine that does what? Have you considered animation events or StateMachineBehaviour for your use case?

steel girder
#

i've considered using the exit animation events however to my knowledge im unable to call instance specific functions for example

#

it'd make it a lot easier if i could use exit animation events though

#

~ also to answer your question it fires off an event to a non mono behavior class listener which changes frequently when the coroutine is done playing the aforementioned animations

queen adder
#

can someone help me make prodecural generation for my 2D sandbox?

steel girder
#

hope the information provided is satisfactory, obviously its a bit convoluted and a not a usual system however, if you're able to provide a better alternative im all ears

wintry quarry
steel girder
#

if im able to subscribe and unsubscribe listeners to the endanimationevents via the class though that'd be more than sufficent

wintry quarry
#

Not sure what you mean by endanimationevents

#

You would need a MonoBehaviour as the listener here. The MB can call a function on your non MB

steel girder
#

preferably this would be done outside the editor

#

i was refering to OnStateExit when i said "endanimationevents"

wintry quarry
#

That's for StateMachineBehaviour

#

Which is the other option I mentioned

steel girder
wintry quarry
#

What issues

steel girder
#

and my terminology wasn't correct

steel girder
wintry quarry
#

StateMachineBehaviour lets you do that

#

OnStateExit gives you a reference to the specific Animator instance

#

From there you can do whatever you want. E.g. GetComponent to grab other scripts on that object etc

steel girder
#

issue being im getting the compile time error CS0201

wintry quarry
#

Sounds like you made some kind of basic C# syntax error

#

But I don't memorize error codes

steel girder
#

thanks for the help in any case friend

#

ill look into what i did further

#

if thats the case

wintry quarry
#

If you need help with the compile error feel free to share the code and the actual error message

steel girder
#

solved my issue thank you friend, basic syntax error was all and i was able to fully solve my initial issue

#

thankuwu i try to think of myself as well versed in Unity and ofc C# however, i guess we all make basic mistakes!

dark hatch
#

how do i make a simple item system, including consumables and items with abilities on activate?

static cedar
#

Make each type of item an object. UnityChanThink
They themselves should be SO.
Then the item slot themselves into structs that holds that item object.

#

The item slot struct can contain things like count or something but most importantly the item representation scriptable object.

queen adder
#

can we serialize a monobehaviour field and make them assignable in inspector, and be used in code for tasks like Destroy(monobfield)

#

like assigning a specific mb field, and not the object

queen adder
static cedar
#

You have three types.

#

List. Slotted. And multi slot occupying system something. UnityChanLOL

#

One is just a list of items. You can sort them or filter.
Second is just a 2d collection of slots.

#

Third is something like Diablo where items can occupy two slots at once in specific shape.

crisp isle
#

can anyone help me out on how to offset an XR controller?

rare basin
#

don't ask to ask

steel girder
# dark hatch thanks

depending on what you want to achieve straight up instances of a item class or instances of a class that inherits from a parent item class could offer more flexibility

#

although for beginners SOs would be better

dapper solstice
#

so if i wanted to damage a player wiht a gun i know i need to send it thru the server first then the client, would i need to make a server script aswell as a script that sits on the player?

charred spoke
dapper solstice
#

mirror with steam works

#

or fizzysteam wokrs

charred spoke
#

Sadly Im not familiar with mirror or steamworks but there is #archived-networking Im sure someone there knows a thing or two

dapper solstice
#

thank you ❤️

static cedar
split dragon
#

Hi, I chose the type of Scripting Backend: "LI2CPP" and I have a problem. I tried to look up a solution to this problem on the Internet, but either there were answers to the old versions of Unity and/or I did not understand how to solve it.
Problem:

keen dew
#

The solution is the same in all versions

#

if you don't understand something then ask

ruby ember
#

but i don't want to use animator or animation

gilded pumice
#

playerRb.velocity = new Vector3.zero;
playerRb.velocity = new Vector3(0,0,0);

can anyone explain to me why I can do the second option but the first one doesn't work? afaik they are the same thing (being used in update method in an if statement if that helps)

the console error doesn't seem to like that I don't have an argument with the .zero, but I'm unsure where I would but the () in the first example.

keen dew
#

Vector3.zero is not a constructor, you don't use new with it

ruby ember
dapper solstice
#

so im trying to make a lobbies list i have all the code but the scroll view isnt showing up neither is the lobbies?

#

and they are active

dapper solstice
wild cargo
#

As for the scrollbar disabling, it is actually functionality implemented by Unity where if the scroll bar would serve no purpose (eg. content folder is not big enough so scrolling does nothing anyways) it will disable set the alpha of it to 0 until it is big enough again

dapper solstice
#

oh ok

ruby ember
wild cargo
wild cargo
#

I've reread #📖┃code-of-conduct and I'm unsure if I'm allowed to help you or not, sorry
(might be wrong here though, as I said I'm not sure)

woven crater
#

hey guys. i want to generate fuction that return random number using a gaussian curve with the magnitue from -1 and 1
the curve take 3 value (a,b,c) where a is the peak value of the curve , b is the lowest value on both end of the curve. c for the ammount of different where c = 0 mean its a straight line with the height of a, the more c increase the curve on both side get steeper

the problem is im bad at math ;w;

#

i want to do this for better number generation , generate from -1 to 1 and take the value on the curve

gaunt ice
#

a must be 1/2
integral from -1 to 1 a dx=2a=1=>a=0.5

#

that means ont of the parameter in your function is fixed

woven crater
#

do i need the intergral to be one?

gaunt ice
#

integral of random variable over its domain must be one

short hazel
#

You can use an AnimationCurve, set it in the Inspector, and .Evaluate() it when needed

woven crater
#

ah thank gah

livid tundra
woven crater
#

imma try the AnimationCurve thing

pure garden
#

Hello, I've been trying to fix this error for days but I just don't understand why it doesn't do it the way I want it even though I actually think everything is correct

Maybe one of you has an idea and could help me...

It would be really great

Kind regards
Ginsmex

This is the video I used for this
https://www.youtube.com/watch?v=ScxN04YeDj8&list=PLZ1b66Z1KFKit4cSry_LWBisrSbVkEF4t

In this tutorial for a 3D Endless Runner we write some code to display out coins collected on screen.
✦ Subscribe: http://bit.ly/JimmyVegasUnityTutorials
✦ Patreon: http://patreon.com/jimmyvegas/
✦ FREE Assets: http://jvunity.com/
✦ Facebook: https://www.facebook.com/jimmyvegas3d/
✦ Twitter: https://twitter.com/jimmyvegas17/

-------------------...

▶ Play video
short hazel
gaunt ice
pure garden
short hazel
#

Okay it's not a Text, it's a TextMeshPro Text you have attached to that object.
The type is different, you need to use TMP_Text in your code

#

The tutorial might be a bit dated and was made before TextMeshPro was the mainstream solution

pure garden
short hazel
#

It's pretty much the only thing that changed sensibly, but you can filter your searches so they only include results from the last two years or so

pure garden
#

OK, thanks for the great help

golden otter
#

is calling a UnityEvent in the Update a bad practice?

wild cargo
#

Use regular c# events whenever possible. Basic syntax is
public Action event MyEvent

golden otter
#

Oh didn't know that

#

Thanks!

static cedar
#

You can opt out of using the event keyword btw.

#

What the event keyword does is prevent other classes from being able to call it.
And you also can't set it. Just add or remove methods to it.

#

Removing the event keywords allows anything to access, set, get, and call it. As long as it's accessible (public and stuff).

wild cargo
#

But then when the event keyword gets removed, you can only assign one thing to it (the action)

#

Delegates should be used in that instance

#

Could be wrong though, been a while since used delegates in my architecture

static cedar
#

I think you can still assign multiple methods in a delegate. I'm not sure tho. :p

wild cargo
static cedar
#

If it's not an event, you can use the readonly keyword.
Or make a getter setter and make the setter private.

wild cargo
#
        public static Action MyAction;

        public void Test()
        {
            MyAction += () => Debug.Log("test1");
            MyAction += () => Debug.Log("test2");
            MyAction.Invoke();
        }

But for some reason, this also leads to the same behaviour.. what?

#

No need for delegates or events

static cedar
#

Lol.

#

Action are delegates.

#

Any delegates can be events.

wild cargo
#

So then when should you use delegates? Never?

static cedar
#

You normally make your own delegates for explitness or something. Or use the ref, in, or out keywords.

wild cargo
#

If you have to write more boilerplate to them then there's no point

static cedar
#

MyDelegateForSpecificThing says more than Action<Here's your input, here's your other input>.

wild cargo
#
        public delegate void MyItemDelegate(int myInt, string myString, ScriptableItemData itemSO);
        public static MyItemDelegate MyDelegateInstance;

        // vs

        public static Action<int, string, ScriptableItemData> MyAction;

Like this maybe?

#

Then the delegates can be reused easier.. but that's like the only benefit

#

And also the param names

static cedar
#

They only need to match signature. :P

short hazel
#

It is a benefit if you have a lot of them, or the same types

static cedar
wild cargo
static cedar
#

But I personally used custom delegates instead of Action. I keep refactoring and I want those warnings.

wild cargo
#

So events are basically useful when you want to create a delegate instance that can only be subscribed to by other classes, not called by

short hazel
#

width, height, length is clearer than arg1, arg2, arg3 so yes custom delegate types are better for these use cases

wild cargo
static cedar
#

I'm pretty sure you only see. MyDelegate.

#

I guess unless you do a lambda?

short hazel
#

You see it in the handler method, as when you make VS auto-create the method, it takes the delegate type's param names for the method name

#

It's useful for when the handler is not in the same type as the one declaring the event

#

And of course as a tool tip when you invoke the event

static cedar
#

Ah.

silent geyser
#

hello!

#

im getting this error and my charachter is floating

#

UnassignedReferenceException: The variable orientation of PlayerMovementTutorial has not been assigned.
You probably need to assign the orientation variable of the PlayerMovementTutorial script in the inspector.

wild cargo
rich adder
#

assign orientation

short hazel
#

That error is one of the clearest you'll be getting in Unity

silent geyser
rich adder
wild cargo
silent geyser
#

and assing it to what

short hazel
#

To whatever the tutorial you're following tells you

#

You might be doing this later in the tutorial, so it's possible to get the error if you test your game too early

silent geyser
#

i downloaded the script

#

and gave it to the 3d charachter

lavish terrace
#

simple saving and loading system ?

silent geyser
short hazel
eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

silent geyser
lavish terrace
silent geyser
#

not for my career

#

xD

short hazel
#

That's not a very good way of thinking

#

If you're not willing to put in any effort, why should we?

#

Do some of the beginner courses on Unity Learn, then come back

silent geyser
#

jki

#

jk

wild cargo
# lavish terrace simple saving and loading system ?

How simple do you want it to be? How much are you willing to learn?
If you want to make a very easy-to-set-up system, learn about PlayerPrefs. It has very easy to understand syntax.
If you want to make a more scalable solution with more types supported, learn about JSONs and serialization. This takes more time but is very much recommended

silent geyser
#

ok i fixed the error

#

but the carema is floating

lavish terrace
wild cargo
#

But JSONUtility is so dogshit I don't recommend using it for a project where you anticipate a lot of saving/loading

lavish terrace
#

that doesnt feel like english

wild cargo
lavish terrace
#

i just need a way to keep my player data when closing/launching the game

wild cargo
#

What does your player data consist of? An inventory, player name, EXP level, stats?

lavish terrace
#

yea kinda

#

the inventory is more of a dicitonary with an int itemid , and a bool to know if its owned or not

wild cargo
#

For that kind of data you could use PlayerPrefs but I highly discourage it, because saving collections with it is troublesome

lavish terrace
#

so thats what basically stressing me out

gilded pumice
#

isnt JSON for programs hosted on servers? At least that's all I've ever seen people talk about/use it for. As in, you wouldn't really use it if your game didn't interact with a server somewhere

rich adder
wild cargo
gilded pumice
#

yeah this makes sense. like I said I've only ever seen it being used to interface with servers, at any rate I'm up to my ears learning C# rn so I stay away from additional concepts for now because it will probably only confuse me further

wild cargo
#

That 4 hours is just an approximation, that's how long it took me to learn the gist of it

lavish roost
#

It Just stores data you can use it for anything

lavish terrace
#

sure its gonna be one of my options which iam exploring right now

#

gonna learn starting with playerprefs

#

ty for help

pliant mist
#

I want an enemy to go to the nearest point on a sphere around the player then try to stay on that circle and while on the circle shoot the enemy, the last part is easy but I'm not sure how to find the nearest point on a sphere

#

how should I begin this?

rich adder
analog depot
#

sorry

#

yup

pliant mist
#

I think if I get a line from the player to the enemy then subtract the radius I can get a good target point

wild cargo
#

You can just use "Random.InsideUnitSphere * radius" and update that every frame the player moves for a random position

vast tangle
#

i have an assignment and im contemplating where to put the difficulty value of the game
Is it best practice to put difficulty value in game manager? or in a static class of sorts?

The plan is to use that value when I start the game in the game manager.

and the value can be changed from a ui list button

pliant mist
wild cargo
wild cargo
rich adder
pliant mist
#

that's okay, do you know how to find a point on a line x distance from the enemy

wild cargo
#

I think just move towards the player and when it is a specific distance away from it, stop moving nd start shooting

pliant mist
#

it was that easy

#

the whole time lol

wild cargo
vast tangle
wild cargo
rich adder
vast tangle
#

Thanks!

rich adder
#

each difficulty SO for me has different values

wild cargo
static cedar
#

Two letters can be pretty hard to google .

vast tangle
#

would this still apply if im loading the difficulty from a json file?

wild cargo
rich adder
#

if you have a json with the data you don't really need SO

wild cargo
vast tangle
dapper solstice
#

can ayone help me out, im trying to make a server browser for steam but every time i go inot the lobbies it doesnt show in the scroll view it spawn ages away

dapper solstice
#

no its got nothing to do wiht networking

rich adder
#

steam/ lobbies is not networking ?

dapper solstice
#

no no

#

hold on

rich adder
#

what is this video supposed to show ?

dapper solstice
#

the prefab isnt spawning on the content

#

it spawn far away from it

rich adder
#

so you outta show both the inspectors for each object involved and the scripts. otherwise its all speculative.

dapper solstice
#

so that where the content is

#

then thats the "lobby" spawning at 1500 pos z

#

when the prefab is set to pos z 0

rich adder
dapper solstice
#

cheers

pliant mist
#

is there a way to calculate the total degrees required to rotate towards something

#

I'm using the rotate towards method but that step thing is a pain, it's not exact so the enemy will always be a little off

lavish terrace
#

i have been using the keyword " new " all the time i just dont have any idea what does it do

#

or mean

frosty hound
#

It means you're creating a new instance of the object type

#

For example, Vector3 is just a class object. You can think of it as a blueprint/template.

When you want a Vector3, you use the new Vector3(...)

lavish terrace
#

ahhhhh ! so that what it does

#

makes alot of sense now

pliant mist
#
float singleStep = rotateSpeed * Time.deltaTime;
Vector3 newDirection = Vector3.RotateTowards(transform.forward, targetDirection, singleStep, 0.0f);

transform.rotation = Quaternion.LookRotation(newDirection);```
#

how do I get single step to be the exact rotation required?

#

at the moment in under or overshoots

wild cargo
pliant mist
#

thanks alot

wild cargo
#

Actually, I might be wrong here

#

Test it and see if it works

#

If it doesn't, use Vector3.Angle() instead. It gets the exact difference between the 2 positions

keen dew
#

Do you mean newDirection overshoots? It wouldn't make sense for the singleStep to over/undershoot

wild cargo
#

So it should just be the upper bound

keen dew
#

RotateTowards is guaranteed to not overshoot so if it doesn't work I assume the problem is with the sprite or model not having its forward vector pointing to the right place

tawny rain
#

!IDE

eternal falconBOT
cosmic dagger
lavish terrace
#

normally i would, however the community here forces you to engage with them 🦧

#

i like the community here 🦦

lavish roost
#

my unity is stuck what do i do?

rich adder
languid spire
cosmic dagger
#

The infinity loop bandit strikes again!

lavish roost
languid spire
#

were you trying to enter play mode?

lavish roost
#

nope

cosmic dagger
#

Do you mean when you focus back to unity from your IDE?

languid spire
#

in that case check the !logs

eternal falconBOT
#
📝 Logs

Documentation

Editor logs

Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log

Unity Hub

Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs

lavish roost
languid spire
#

you're still gonna have to kill the process, hopefully nothing will be corrupted

cosmic dagger
languid spire
#

are you in debug mode in VS ?

lavish roost
lavish roost
#

after trying to attach but it doesnt solve anything

languid spire
#

I wonder if there is an artifact still locked by VS, try closing VS, it may free up the Unity process

cosmic dagger
#

Oh, unity automatically recompiles when you save from VS? Try closing VS and reopening it. I didn't know that . . .

languid spire
#

it does, but only when the VS instance is attached to a Unity instance

lavish roost
#

i killed the vs instance unity is still blocked, interesting bug

languid spire
#

indeed, seems like some kind of race condition, I fear kill Unity is the only solution

lavish roost
#

i can just kill the unity instance and get the backup scene right

languid spire
#

you had unsaved changes?

lavish roost
#

yeah

languid spire
#

oops

#

yes, you should be able to get the scene backup before you open Unity again

lunar tapir
#

Hi, how can I increase the size of this window in Visual studio?

#

what is this window called? idk what to search for basically

fierce shuttle
queen adder
lunar tapir
#

becomes smaller with this theme for some reason, I'll just change back the theme

queen adder
#

Ok

rich adder
#

dont think that works on the suggestion box

fluid badger
#

I'm new to unity, what exactly does FixedUpdate() func versus Update()?

frosty hound
#

Fixed runs every physics step, Update runs every frame.

fluid badger
#

So I assume I can change the physics update rate?

frosty hound
#

You can, technically. It's not something you normally would need to/want to do.

queen adder
gaunt ice
#

50fps by default

dry hare
#

what do you mean "what about update?"

rich adder
#

btw its prob because my pivot is at the feet and yours at the center, all you gotta do is remove the Y from world pos

dry hare
#
    void Update()
    {
    Plane ground = new(Vector3.up, Vector3.zero); 
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);





    float horizontal = Input.GetAxisRaw("Horizontal");
    float vertical = Input.GetAxisRaw("Vertical");   
    Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
    if(controller.isGrounded && _velocity < 0f)
    {
        _velocity = -1.0f;
    }
    _velocity += _gravity * GravityMultiplier * Time.deltaTime;
    if(_velocity < -53f){
        _velocity = -53f;
    }
    

    if(Input.GetKey(KeyCode.LeftControl)){
        Cursor.visible = false;
        Cursor.lockState = CursorLockMode.Confined;
        if(ground.Raycast(ray, out float distance)){
            Vector3 worldpoint = ray.GetPoint(distance);
            var dir = (worldpoint - transform.position).normalized;
            transform.forward = dir;
        }
        

    }```
#

that's the part that should matter

#

everything else is just movement stuff

rich adder
#

Vector3 worldpoint = ray.GetPoint(distance);

#

you're still using local variable

#

you never writing the variable you made

#

remove Vector3. should be worldpoint = ray.GetPoint(distance);

#

from that

#

but anyway it will still slightly rotate cause ur pivot is in the middle of player and not like feet like mine

dry hare
#

yea alright did that

#

yea it does the thing now

#

so from here how would i make it just twist on the y and nothing else?

rich adder
dry hare
#

does the same thing but... backwards??

zenith cypress
#

Why are you setting the y direction to a world point

dry hare
#

wdym

rich adder
# dry hare

ya that should be

worldPoint = ray.GetPoint(distance);
            worldPoint.y = player.transform.position.y;
            var dir = (worldPoint - player.transform.position).normalized;
            player.transform.forward = dir;```
#

myb

#

i think

zenith cypress
#

Yes

dry hare
#

YES it works now

#

thanks

zenith cypress
#

Or if you don't want y, as it seems, just set y to 0 in the direction

rich adder
#

sorry I didnt take my caffeine yet xD

#

ay yeah I think meant to 0 out that and mixed it with the second

amber spruce
#

hey so i want to have it so while a bool is true then it heals you every 2 seconds

#

how would i achieve that

rich adder
amber spruce
#

how do i make sure the coroutine doesnt fire again beofre the previous one finishes

rich adder
rich adder
amber spruce
#

and i assume the healing is the bool to say you are healing right

rich adder
amber spruce
#

and healingRoutine is a coroutine variable?

rich adder
#

@amber spruce you prob dont even need coroutine var you can just check if(healing) return; out the StartCoroutine func

#
void Healup()
    {
        if (healing) return;
        StartCoroutine(Healing());
    }
    private IEnumerator Healing()
    {
        healing = true;
        while (healing) //set healing to false to exit
        {
            //Heal
            yield return new WaitForSeconds(2);
        }
    }```
amber spruce
#

nvm

#

i know what i did wrong lol

rich adder
#

cache it once

#

doing that in a while loop is just as bad as doing in update

amber spruce
#

yeah ik but im only really gonna use it once for healing thats it

rich adder
#

but you call it every 2 seconds

amber spruce
#

fixed it

waxen oracle
#

If i used,

obj = GameObject.Find(“Checkpoint”)
dis = Vector3.Distance(transform.position, obj.transform.position)

When there are multiple objects called checkpoint, what would happen

languid spire
#

it would return the first one it came across

rich adder
#

better alternative, have the checkpoints already stored in an array

waxen oracle
#

I could do that

#

Do for loops exist in c sharp

#

or an equivalent

waxen oracle
#

oh the for loops are like the gml ones

#

Ty

rich adder
quaint axle
#

Hi, here are the script of each pipe object

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PipeMoveScript : MonoBehaviour
{

    public float moveSpeed = 5;
    public float deadZone = -45;

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

    // Update is called once per frame
    void Update()
    {
        if (transform.position.x < deadZone) {
            Debug.Log("Pipe Destroyed");
            Destroy(gameObject);
        }

        transform.position = transform.position + (Vector3.left * moveSpeed) * Time.deltaTime;
    }
}

#

And here the script of the spawn of these pipes :

using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class PipeSpawnScript : MonoBehaviour
{
    public GameObject pipe;

    public float spawnRate = 2;
    private float timer = 0;
    private float lastPipePosition = 0;
    public float heightOffset;
    public float diffOffset;
    public float acceptedOffset;


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

    // Update is called once per frame
    void Update()
    {
        if (timer < spawnRate)
        {
            timer += Time.deltaTime;
        } else
        {
            spawnPipe();
            timer = 0;
        }
    }

    void spawnPipe()
    {
        float lowestPoint = transform.position.y - heightOffset;
        float highestPoint = transform.position.y + heightOffset;

        float newPipePosition = Random.Range(lowestPoint, highestPoint);

        Debug.Log(newPipePosition - lastPipePosition);

        if (Mathf.Abs(newPipePosition - lastPipePosition) > acceptedOffset)
        {
            newPipePosition = lastPipePosition + Mathf.Sign(newPipePosition - lastPipePosition) * diffOffset;
        }

        lastPipePosition = newPipePosition;
        Instantiate(pipe, new Vector3(transform.position.x, newPipePosition, 0), transform.rotation);
    }
}

I'd like to change the moveSpeed of the pipes each time I pass trhough the middle of them the same way I do it for the score but as the pipes are instantiated multiple times due to the spawn function I don't find a good way to do it.

#

The detail of the code is not really important I just want to know how to change the moveSpeed variable each time I trigger the bird in an other script for all pipes (past and future so they all change the same at the same time)

#

For the score I do it with a tag but here it doesnt seems to work, I also tried with a list but I don't think its a good way to handle this and it didnt work anyways

charred spoke
# quaint axle The detail of the code is not really important I just want to know how to change...

Sounds like a job for the flyweight pattern https://refactoring.guru/design-patterns/flyweight I would have a singleton that holds the relevant pipe data like speed and have the pipes read their speed from that one central place. That way if you increase the speed variable of the singleton all pipes will read the new value

lavish terrace
#

any idea whats the theme used here?

gaunt ice
#

no code question
you can ctrl K, then ctrl T choose the theme

lavish terrace
#

yea sorry about that

#

but thanks

brittle plume
#

how do i post code here?

river roost
#

!code

eternal falconBOT
brittle plume
#

thanks

#


public class Flashlight : MonoBehaviour
{
    public GameObject flashlight;
    public bool isOn;
   public Enemy enemy;
    // Start is called before the first frame update
    void Start()
    { 
        isOn = false;
    }

    // Update is called once per frame
    void Update()
    {
          if (Input.GetKeyDown(KeyCode.F))
        {
            if (isOn == false)
            {
                isOn = true;
               flashlight.SetActive(true);
               enemy.sightDistance = 20f;
            }
            else
            {
                isOn = false;
                flashlight.SetActive(false);
                enemy.sightDistance = 0f;
            }
        }
    }
}
#

im getting a nullreference error both lines with enemy.sightDistance in them

#

how would I fix it?

river roost
#

enemy is null

gaunt ice
#

where you assign enemy

brittle plume
#

how do i assign enemy

river roost
#

Probably in the inspector

brittle plume
river roost
#

You have to assign it on the Flashlight script

brittle plume
#

should there be a place to assign it?

river roost
#

There should be, that's odd

#

If you ctrl click "Enemy" in the flashlight script it shows you the Enemy MonoBehaviour right?

brittle plume
#

yes

#

brings me to the enemy script

river roost
#

You don't have a custom editor?

brittle plume
#

I use visual studio

river roost
#

I meant a custom inspector

brittle plume
#

oh

#

whats that

river roost
#

you don't have one, but yeah I don't know what could be causing this

#

Did you change the file name of the Flashlight script?

brittle plume
#

no

river roost
#

try restarting unity maybe?

brittle plume
#

alright

#

i'll let you know

acoustic current
#

how do i add something (like webGL support) to an editor version?

river roost
acoustic current
brittle plume
river roost
#

nice!

#

thats really odd though

brittle plume
#

yeah

#

i spent atleast an hour trying to figure that out 😭

#

and it was just a restart

river roost
acoustic current
#

updated unity hub, still no option

languid spire
keen dew
#

You're trying to add it to a project. Open the installs page.

#

and the editor has to have been installed through the Hub, if not then you can't add modules to it

acoustic current
#

my bad

acoustic current
#

but it didnt show the option

#

im gonna install a new version and add it to that

#

and then remove this old and bugged version

knotty gust
#

how would i program a game object to add itself to an array in the editor instead of at runtime

amber spruce
#

how do i reload the current scene?

#

so like go back to the start of it

knotty gust
amber spruce
#

so i can copy and paste that and it should work i dont have to change anything

knotty gust
#

pretty sure but there might be better ways

amber spruce
#

it should work for now thanks

vast tangle
#

If anyone could give me pointers on how to approach this possibly let me know 🙂
I have this object (hollow circle)
and depending on the amount of cuts I ask for it creates separate objects

1 cut gives 2 objects
2 cuts gives 3 equal objects etc.
The more I think about it the more its like a pie chart with equal values
but I do want to seperate them with spacing so it looks like a simon says button board.
anyone have any pointers? 🙂 thanks!

Edit: found this tutorial
https://www.youtube.com/watch?v=9fgZ286pPcY&t
but if anyone has anything to share im keeping my post 🙂

unreal phoenix
#

Anyone know why my models Y rot in the inspector is behaving as a -Z rot?

cosmic dagger
potent echo
#

Hey folks, how can I use Random **not **to select a number between two choices, but rather one of the choices themselves? (Similar to random.choice in python)

verbal dome
languid spire
unreal phoenix
knotty gust
#

how would i program a game object to add itself to an array in the editor instead of at runtime