#💻┃code-beginner

1 messages · Page 31 of 1

young warren
#

Never named a variable and method the same before

queen adder
#

😄 yes somehow it does not allows

young warren
#

Is it really the issue?

#

Not that you have 2 methods with the same name

queen adder
#

Nope but i wonder if it can get fixed

young warren
#

No, I'm asking you if the problem is really that the variable and method is the same name

#

You could check by just naming the variable something else temporarily to see

timber tide
#

Make the compiler happy and do what it says

queen adder
#

Thank you rat, wytea UnityChanThumbsUp

hidden citrus
#

is it possible to add knockback force to a navmesh agent? Looks like they're conflicting setups. If a rigid body uses gravity and a nav mesh, itll work, but then the agent will slide. The only alternative i can think of is "turn off agent while knocked back coroutine is running" then switching it back on

timber tide
#

I do dislike not being able to named my enums the same name as the type if they are nested within the class. :(

timber tide
#

still probably ways about it. Disabling the pathfinding as its knocked back does sounds like the solution, but you lose the feature of a character fighting against the pushing force.

magic stream
#

Player goes through all objects, he doesn't collide with anything.

tender stag
#

is this a good way of getting a percentage?

flat slate
#

eyo why doesnt my Button work?

summer stump
flat slate
#

ye

gray arrow
#

Hey guys, yet another problem from me ha

so, im trying to make a top down shooter, and my current goal is making the camera move in front of the player (relative to the player's rotation) when they scope in.

however, my problem is that sin() and cos() output positive numbers with negative inputs. this means that an angle of -45 is treated the same as 45, which makes the camera completely broken.

is there an easy way to fix this?

here is the code for the camera if you need it: (lineOfSightOffset is the distance from the player that the camera should be)

if (Input.GetKey(KeyCode.Mouse1))
        {   
            // 1. Get the sprite's rotation Quaternion 
            Quaternion spriteRotation = Player.transform.rotation;

            // 2. Convert the Quaternion to Euler angles
            Vector3 spriteEulerAngles = spriteRotation.eulerAngles;

            // 3. Extract the angle you need (in degrees)
            float rotationAngleDegrees = spriteEulerAngles.z;

            transform.position = new Vector3(Player.transform.position.x + (LineOfSightOffset * Mathf.Cos(rotationAngleDegrees)), Player.transform.position.y + (LineOfSightOffset * Mathf.Sin(rotationAngleDegrees)), 0);
        }
        else
        {
            transform.position = new Vector3(Player.transform.position.x, Player.transform.position.y, 0);
        }
summer stump
ashen ferry
#

How come my lil loading screen still freezes with async scene loading seems like it alleviates it a bit but can I somehow always keep some time in frame for my loading screen script to run so it would be seamless

tender stag
#

and when repairing in the code above

#

i need to get a random percentage

#

and if its in the percentage it needs to break

#

but if its not you repair the item

#

and then increase the break probability

magic stream
#

By saying it doesn't work I mean that player goes through all objects.

modest dust
flat slate
modest dust
#

And it doesn't increase, it decreases

summer stump
#

Show a screenshot of your inspector

#

With the button selected of course

summer stump
flat slate
#

can u read it?

sharp stag
#

Hey everyone i'm trying to make a first person shooting game but I want some cutscenes to make it switch to TPS, I've already prepared both cameras but I can't manage to change it in Timeline. I already did the cutscene animations and such

flat slate
dim basin
#

!learn

eternal falconBOT
#

🧑‍🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

glossy eagle
#

Hi. One question, what are those things called please? Like those things that go [] above the variables or something. Because I would learn more about them to be able to do some stuff with those variables under them:

summer stump
glossy eagle
#

okay thanks

flat slate
#

its for a dialogue

summer stump
#

It has to be an OBJECT in the scene that HAS the script on it

flat slate
#

okay wait

dim basin
#

do i use anywhere commands or there ic channel for them?

dim basin
#

there server commands

#

like learn

summer stump
#

Yeah there are

dim basin
#

(idk where to ask them)

summer stump
#

What do you need

dim basin
#

is there channel for them

summer stump
#

No

dim basin
#

oh k

summer stump
#

Oh shi- didn't know lol

rich adder
#

🙂

gray arrow
#

Hey guys, yet another problem from me ha

so, im trying to make a top down shooter, and my current goal is making the camera move in front of the player (relative to the player's rotation) when they scope in so they can see further.

however, my problem is that sin() and cos() output positive numbers with negative inputs. this means that an angle of -45 is treated the same as 45, which makes the camera completely broken.

is there an easy way to fix this?

here is the code for the camera if you need it: (lineOfSightOffset is the distance from the player that the camera should be)

        {   
            // 1. Get the sprite's rotation Quaternion 
            Quaternion spriteRotation = Player.transform.rotation;

            // 2. Convert the Quaternion to Euler angles
            Vector3 spriteEulerAngles = spriteRotation.eulerAngles;

            // 3. Extract the angle you need (in degrees)
            float rotationAngleDegrees = spriteEulerAngles.z;

            transform.position = new Vector3(Player.transform.position.x + (LineOfSightOffset * Mathf.Cos(rotationAngleDegrees)), Player.transform.position.y + (LineOfSightOffset * Mathf.Sin(rotationAngleDegrees)), 0);
        }
        else
        {
            transform.position = new Vector3(Player.transform.position.x, Player.transform.position.y, 0);
        }```
rich adder
#

did you get it sorted ?

echo dove
#

Nope 😦

#

i tested it out nothing works

rich adder
#

hmm strange, lets see where you left off

echo dove
#

should I send code?

rich adder
#

yeah use paste site

echo dove
#

whats that

rich adder
eternal falconBOT
#
Posting code

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

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

wintry quarry
echo dove
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class BulletSpawn : MonoBehaviour
{
    private float cd;
    public Transform pTrans;
    [SerializeField] private GameObject bullet;
    public InputActionReference gamepadRight;
    // Start is called before the first frame update
    void Start()
    {
        gamepadRight.action.Enable();
    }

    // Update is called once per frame
    void Update()
    {
        cd += Time.deltaTime;
        if (gamepadRight.action.triggered && cd >= 0.5)
        {
            Debug.Log("Click worked");
            Instantiate(bullet, new Vector3(transform.position.x ,transform.position.y,0),transform.rotation);
            cd = 0;
        }
    }
}
#

I think my problem is with the instantiate

#

It probably is

wintry quarry
summer stump
#

Oh

#

Like praetor said

gray arrow
#

i not sure if that will account for direction

rich adder
gray arrow
#

ill do it and get back to you

echo dove
#

my player

#

and the ai but ai has a different script

wintry quarry
#

(this is assuming a 3d game btw)

gray arrow
#

its 2d

wintry quarry
#

then use transform.right instead

#

otherwise the same

gray arrow
#

ok

rich adder
echo dove
# rich adder possibly, which object has this script on it ?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class AIFollow : MonoBehaviour
{

    [SerializeField] private GameObject bullet;
    public Transform player;
    private float time;
    public float times = 1.5f;
    public float moveSpeed = 12f;
    private Rigidbody2D rb;
    private Vector2 movement;

    // Start is called before the first frame update
    void Start()
    {
        rb = this.GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        shoot();
        Vector3 direction = player.position - transform.position;
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        rb.rotation = angle;
        direction.Normalize();
        movement = direction;
    }
    private void FixedUpdate()
    {
        moveCharacter(movement);
    }
    void moveCharacter(Vector2 direction)
    {
        rb.MovePosition((Vector2)transform.position + (direction * moveSpeed * Time.deltaTime));
    }
    void die()
    {
        Destroy(gameObject);
    }
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.gameObject.CompareTag("Bullet"))
        {
            die();
        }
    }
    private void shoot()
    {
        time += Time.deltaTime;
        if(time >= times)
        {
            Instantiate(bullet, new Vector3(transform.position.x, transform.position.y, 0), transform.rotation);
            time = 0;
        }
    }
}

Here is my ai script(It also does not shoot but does move)

flat slate
#

the thing is i just copied the button to another scene

flat slate
#

in the other scene it works

summer stump
rich adder
flat slate
rich adder
#

the red should be pointing the same way as barrel @echo dove

summer stump
rich adder
#

and the green should be your Left side of character @echo dove

flat slate
#

what is the event system?

echo dove
summer stump
summer stump
rich adder
# echo dove how do I change it

righ click on player, make a new gameobject on the player, move it out of the player object after..Make sure now points correct way, put it back on your player and use that as your shoot-BulletSpawn script / origin

summer stump
gray arrow
#

i thought transform.forward was another shorthand like vector3.up not sure why

flat slate
gray arrow
flat slate
summer stump
flat slate
#

now it works

gray arrow
#

one thing i do want to know, is is there a way to modify transform.position.z without writing the whole thing as a Vector3 and changing the z part?

rich adder
# echo dove So I have to redo my model?

if its a sprite you can fix the pivot in sprite editor, it doesnt matter tho you can just make an empty gameobject for this just as Firepoint then use that in instantiate with a reference to that transform

wintry quarry
#
Vector3 pos = transform.position;
pos.z = whatever;
transform.position = pos;

or use an extension method:

public static Vector3 WithZ(this Vector3 input, float newZ) {
  input.z = newZ;
  return input;
}

// THen you can do this
transform.position = transform.position.WithZ(whatever);

Or add somthing:

transform.position += Vector3.forward * amountToChange;```
rich adder
echo dove
#

But what is this fixing?

#

nothing changed

rich adder
echo dove
rich adder
#

probably need to fix the bullet as well

echo dove
#

the pivot?

rich adder
# echo dove the pivot?

show prefab for it
you try making a new bullet thats just a 2D circle sprite and see if it works

echo dove
#

ok

rich adder
#

lol

#

you don't see the problem

echo dove
rich adder
#

look carefully

echo dove
#

Yep I saw..

#

the bullet is way of

#

Idk how it happened

rich adder
#

indeed

#

probably when you worked in Center pivot On

echo dove
#

So I should make a new bullet prototype

jolly igloo
#

Hi. Im struggling to make the pipes spawn in my flappy bird game. The pipes spawn but they don't spawn in the right place

rich adder
# echo dove yep

its very strange thing that unity makes it default , it can cause such issues ..

jolly igloo
#

I can show you the code

echo dove
#

Yep thx so much for ur help

jolly igloo
#

Ok

rich adder
jolly igloo
#

Yes, a little bit

#

Just the spawning part

rich adder
#

share !code

eternal falconBOT
#
Posting code

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

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

jolly igloo
#

This

echo dove
#

He means send the code in a website

rich adder
echo dove
#

oh

flat slate
#

i need help

rich adder
summer stump
echo dove
rich adder
echo dove
#

Here is my code

summer stump
#

Missing semicolon

rich adder
#

ur missing variable name

summer stump
#

And name. Line 10

echo dove
#

Oh yeah thx

#

I am so stupid ...

rich adder
#

at least your IDE is configured

echo dove
#

I thought it was some kind of error with my code but it is with my brain

echo dove
rich adder
#

your code editor , Visual Studio

#

(integrated development environment)

echo dove
#

oh okay

echo dove
#

ah wait sorry

echo dove
jolly igloo
echo dove
#

Then why are you not sending the code :.

#

:/

jolly igloo
#

I was studying

#

Sorry

echo dove
#

alr

jolly igloo
#

I'll send it

#

Jsut need like 5 minutes

jolly igloo
#

public class PipeSpawnScript : MonoBehaviour
{
public GameObject Pipe;
public float Spawnrate = 2;
private float timer = 0;
public float heightOffset = 10;

void Start()
{
    spawnPipe();
}

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

void spawnPipe()

{
    float lowestpoint = transform.position.y - heightOffset;
    float highestpoint = transform.position.y + heightOffset;

    Instantiate(Pipe, new Vector3(transform.position.x, Random.Range(lowestpoint, highestpoint), 0), transform.rotation);
    
}

}

#

i dont know how to paste it better

jolly igloo
warm raptor
#

I have a problem in my script in this part:

Debug.Log("New Player arrived");
GameObject playerInstance = Instantiate(PlayerPrefab, Vector3.zero, Quaternion.identity);
Debug.Log("Player spawned");
ConnectedPlayer.Add(NewID);
Debug.Log(ConnectedPlayer);

when I launch a second session of the game, I see the New Player arrived log looping in the console but I do not see the Player spawned and no player is instantiated. in the hierarchy I don't see any player appearing even in 0,0,0

jolly igloo
rich adder
rich adder
#

yea but we need to know what "in the right place" means

#

eg screenshot some spawn points, and where its spawning instead

jolly igloo
#

basicaly some pipes are blocking the scene when they spawn and the bird cant pass

#

ill show you a pic

short hazel
# warm raptor I have a problem in my script in this part: ```cs Debug.Log("New Player arrived"...

Two options here.

  1. On the second client, somehow PlayerPrefab is null, which makes Instantiate throw an exception, stopping the execution immediately (hence no log and no player instantiated). You'll get a "the object you want to instantiate is null!" error in the console.
  2. The whole ws.OnMessage handler here runs in another thread, and accessing most Unity stuff (instantiating objects included) from another thread terminates the thread immediately without warning.
ashen ferry
#

how do u navigate fast in rider to a class u know name of but dont have it used in code on hand for ctrl click like if ive got ClassA so I press some shortcut type that in and it opens me definition somewhere in my scripts

rich adder
# jolly igloo

alr where did you place your spawn point at in the scene view

#

also show prefab for pipe

wide dove
#

hi im trying to make a scene that plays a video, i want it to play the next scene when the video ends

#

but i cant

rich adder
#

you can't why ?

jolly igloo
rich adder
echo dove
#

xD

#

is it the same problem with me

rich adder
#

might be xD

jolly igloo
#

wait nvm

echo dove
#

top left

#

@jolly igloo your problem might be that the y offset is to big

#

make it smaller

jolly igloo
#

ok

jolly igloo
rich adder
echo dove
#

show me a video

#

@jolly igloo

jolly igloo
#

ok

#

how do I record tho

rich adder
#

obs

rich adder
jolly igloo
echo dove
#

it wont refresh

#

change in inspector

rich adder
jolly igloo
#

ok

echo dove
#
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Bullet"))
        {
            die();
        }
    }
    void die()
    {
        BroadcastMessage("check", 0);
        Destroy(gameObject);
    }

Hi I dont get it why this broadcast isn't working pls help

    void check(float yes)
    {
        Debug.Log(yes);
        if(yes == 0)
        {
            die();
        }
    }
#

the first is for my player

#

the second is my ai

#

I am trying to tell that when the player dies the ai also dies

#

Hey navarone can I ping you 🙂

jolly igloo
#

it works now

#

thank you so much

echo dove
rich adder
runic terrace
echo dove
echo dove
rich adder
#

Just don't use that function at all, its slow / brittle

echo dove
#

how Can I deliver messages or functions to others with an if statement

rich adder
#

just reference the script and call the function directly

#

later on you learn about real events

#

like Action

#

or UnityEvent

echo dove
twilit nest
#

Het I'm trying to rotate a head along the Z axis. In the Scene editor it automatically adjusts for the position aswell. How do I do this in code when I just try to edit the Z rotation it goes around the player body.

This is the current code I use for rotating the head.

y = Input.GetAxis("Mouse Y");

Vector3 headCenter = bodyHead.transform.position + bodyHead.transform.up * radius;

bodyHead.transform.rotation = Quaternion.Euler(bodyHead.transform.eulerAngles.x, bodyHead.transform.eulerAngles.y, bodyHead.transform.eulerAngles.z + y * sensitivity);
rich adder
#

second one is better

echo dove
#

oh yeahh

#

so do I do

rich adder
#

your current function still doesn't make much sense

dry tendon
#

is there any way to execute a function even before the unity animation on android is being executed?

rich adder
dry tendon
#

yeah

rich adder
#

what is that?

#

you mean the logo splash screen ?

ashen ferry
#

can I serialize DateTime

rich adder
#

make a struct

echo dove
#

How do I check if the function was activated?

void check()
{
    if (script.die)
    {
        die();
    }
}
#

that doesn't work

echo dove
#

wdym

dry tendon
# rich adder you mean the logo splash screen ?

exacly... I need to charge something before that spash screen end... and even i make that splash screen larger the function awake is always executed a few miliseconds before that splash screen ends

rich adder
echo dove
#

hmm okay lemme mess around

rich adder
#

true / false

echo dove
#

is it okay for me to ping you next time if I need help

rich adder
#

only if it pertains to a problem I've responded to, don't ping me for every issue you have lol

echo dove
#

ok

rich adder
#

other people here are very capable to respond lol

rich adder
echo dove
#

I thought of making a variable

#

and tuning it true when the player dies

#

thus have information from that variable and when it does become true the ai also dies

rich adder
#

alright , only issue so far its private

dry tendon
echo dove
#

But Idk how to extract variables from scripts

echo dove
rich adder
#

they need to be public

echo dove
echo dove
rich adder
echo dove
#

Nope the ai doesnt die

#

ah wait

rich adder
#

so only 1 thing checks the bool

#

instead of all enemies

#

reduces code

echo dove
#

so I should make the ai a prefab?

rich adder
#

instead of all enemies checking for player bool

dry tendon
rich adder
#

thats more spaghetti then it needs to be

echo dove
#

oh okay

rich adder
#

[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen)]

dry tendon
#

@rich adder so if this is the method i need to execute before the splash screen it will be something like this? ```cs
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen)]
private void Awake()
{
// Solicitar permisos de ubicación (puede personalizar este mensaje)
if (!Permission.HasUserAuthorizedPermission(Permission.FineLocation))
{
Permission.RequestUserPermission(Permission.FineLocation);
}

    // Comprobar si se tienen permisos de ubicación
    if (Permission.HasUserAuthorizedPermission(Permission.FineLocation))
    {
        StartCoroutine(GetLocationData());
    }
    else
    {
        Debug.Log("No se otorgaron permisos de ubicación.");
    }```
#

no, definetly is not like that

sharp stag
#

hey any chance anybody knows how to switch cameras during timeline, my case I've a first person game which I want some third person cutscenes with timeline but I couldn't find how to swap cameras, I've 2 cameras ready (FPS and TPS)

warm raptor
# short hazel Two options here. 1. On the second client, somehow `PlayerPrefab` is null, which...

I don't really understand what's the second options, and I'm sure that it can't be the first one because I don't get any warning or error in the console
also I tried with this code and here the player spawn without any problem

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

public class TESTINSTANCIATE : MonoBehaviour
{
    public GameObject PlayerPrefab;
    GameObject player;
    void Start()
    {
       player = Instantiate(PlayerPrefab, new Vector3(0,1,0), Quaternion.identity);
    }
}
rich adder
oak mist
#

im trying to send the location of my turrent angle to a server in Matlab, heres my code: ```c
public class Server : MonoBehaviour
{
TcpListener server;
TcpClient client;
NetworkStream stream;

void Start()
{
    try
    {
        server = new TcpListener(IPAddress.Any, 8080);
        server.Start();
        Debug.Log("Server started.");
    }
    catch (SocketException e)
    {
        Debug.Log("SocketException: " + e);
    }
    catch (System.Exception e)
    {
        Debug.Log("Exception: " + e);
    }
}
// Update is called once per frame
void Update()
{
    string message = Rotation.currentAngle.ToString();
    Debug.Log("Data being sent");
    Debug.Log("Stream: " + (stream != null));
    Debug.Log("Rotation.currentAngle: " + Rotation.currentAngle);
    Debug.Log("Client: " + (client != null));
    byte[] msg = Encoding.ASCII.GetBytes(message);
    stream.Write(msg, 0, msg.Length);
}

}

rich adder
cunning eagle
#

does anyone know how to stop a character falling through the floor? ive tried looking ways online how to stop it and its not doing anything. this is the code im using

#

im following this tutorial and everything worked fine until the last 5 minutes

#

#survivalgame #tutorial #unity
In this tutorial series, we will create a 3D survival game with Unity & C# as the scripting language.
We are going to start with basic FPS movement, build an inventory, and crafting systems.
Learn how to pick up items and more.
Little by little, we are going to add different features that are common to survival op...

▶ Play video
#

now everytime i play test it i just fall through the terrain

eternal falconBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

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

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

short hazel
# warm raptor I don't really understand what's the second options, and I'm sure that it can't ...

It's the second option then. Your websocket client/server here probably runs on a separate thread to not block Unity's code. You need to create a way to pass your websocket messages to the main thread (the one Unity runs on). Probably using a ConcurrentQueue<T>, that's a collection that allows cross-thread operations, meaning you can add elements from one thread and remove them from another. This definitely isn't a beginner topic though

gaunt ice
#

you want to send angle to server but why you start a server in your code?

cunning eagle
rich adder
#

also multiplying time mouse by delta time is wrong

#

remove that

cunning eagle
#

i didnt make it its from a tutorial im following and everything was working until my character just keeps falling through the terrain

rich adder
#

well the tutorial is wrong

#

and if you're falling through the floor then you don't have collider on floor, or you messed up the grounded layer

warm raptor
cunning eagle
#

there is a collider

rich adder
cunning eagle
#

sorry this is literally like my day 1 of coding and everything was working fine until now

ruby python
#

Anyone? Pleasings? 🙂

dry tendon
cunning eagle
rich adder
cunning eagle
#

I made a new layer for the terrain called ground

rich adder
#

show player fancy loading or somehting

#

shouldn't take long since its an API call but those are ones you use async for this exact reason

#

you want the data to be ready before doing anything (ofc unless you have no connection or anything exception)

rich adder
cunning eagle
#

if i put the player up really high like this sometimes it doesnt fall through but it still stays up really high

cunning eagle
rich adder
cunning eagle
rich adder
echo dove
rich adder
#

did you drag the playercode in the slot?

echo dove
#

oh no

#

thx

rich adder
echo dove
#

Hey I gtg i will be back in 10min

rich adder
#

also u already have player's transform thru this script now
PlayerCode script

solid cove
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerController : MonoBehaviour
{

    public float moveSpeed = 1f;
    public ContactFilter2D movementFilter;


    public float collisionOffset = 0.05f;

    Vector2 movementInput;

    Rigidbody2D rb;

    List<RaycastHit2D> castCollisions = new List<RaycastHit2D>();
   
    // Start is called before the first frame update
    void Start()
    
    {
        rb = GetComponent<Rigidbody2D>();
    }


    private void FixedUpdate() {
        if(movementInput != Vector2.zero){
        int count = rb.Cast(
            movementInput,
            movementFilter, 
            castCollisions,
            moveSpeed * Time.fixedDeltaTime + collisionOffset);

            if(count == 0){
            
            rb.MovePosition(rb.position + movementInput * moveSpeed * Time.fixedDeltaTime);
        }
        if(count != 0){
             print(movementFilter);
             print(castCollisions);
        }
       
    }
    }
    void OnMove(InputValue movementValue) {

        movementInput = movementValue.Get<Vector2>();
        }
}




rich adder
# solid cove oops

a screenshot of playerscreen with inspector expanded would've ben fine

solid cove
rich adder
solid cove
rich adder
# solid cove

try keeping the sleeping mode to Never Sleep on rigidbody, see if it helps

solid cove
#

Still the same thing happening

#

maybe it could be the sprite hitbox? i dont see why but just throwing it out there

echo dove
#

I need that for the ai to navigate the player

#

And doesn't the ai destroy itself how come it is sending commands that it needs the players transform?

rich adder
# solid cove

which layer is player in? maybe it needs to be in its own layer

solid cove
#

default

rich adder
echo dove
#

I tested it

#

it isn't coming from the ai it is coming from the camera xD

#

because when the player dies apparently the camera doesn't get any transform

#

anyways thanks

rich adder
echo dove
#

ok mb

rich adder
#

usually tells you which script has error

echo dove
#

thx

twilit nest
cunning eagle
rich adder
#

also look the Y posiiton in playmode, does it keep moving?

tender stag
#

how can i make foreach run once for every requirement? its in update ```cs
private void Update()
{
if(inputCell.item)
{
Item inputItem = inputCell.item;
IDurable durableItem = inputItem as IDurable;

    breakText.text = "Break %: " + (inputItem as IDurable).BreakPercentage.ToString("F0") + "%";

    foreach(var requirement in inputItem.GetProcess<RepairProcess>().repairRequirements)
    {
        templateName.text = requirement.item.itemData.name;
        templateSprite.sprite = requirement.item.itemData.sprite;
        templateAmount.text = "x" + requirement.amount;

        GameObject newTemplate = Instantiate(template);
        newTemplate.transform.SetParent(content);

        templates.Add(newTemplate);
    }
}
else
{
    breakText.text = "";

    if(templates.Count > 0)
    {
        templates.Clear();
    }
}

}```

#

maybe check if the list doesnt already contain the newTemplate?

river roost
flint pilot
#

Good evening everyone, sorry for this question, I would need some help regarding a mini project but since this is the first time I put my hand to code for VR I would like to know if someone could write the code for me so I can reverse engineer. I need to create some basic interactions for VR but without using external plugins, these interactions I need to take apart the bolts of a car and change the tire. If anyone can help me out I would really appreciate it.

hearty imp
#

When I start coding a game if I wanted to put it on steam would I have to code that game with that in mind?

queen adder
#

how would I make something like Jackbox Games in Unity?

queen adder
#

basically they make these party pack games https://www.youtube.com/watch?v=_JyGUWviG2k

I ranked EVERY JACKBOX GAME from worst to best. Yes. All 45 individual game from the 9 party packs! With that many games to cover, there's bound to be disagreement, but I think any fan of Jackbox will enjoy!

►TWITCH: https://www.twitch.tv/Macro
►TWITTER: https://twitter.com/TheMacroShow
►INSTA: https://instagram.com/TheMacroShow
►MERCH: https:/...

▶ Play video
summer stump
dusk musk
#

Hey everyone! Can someone help me with an issue with my game? In my game the player moves a box to catch balls. When the player moves too fast, the balls "phase" through the walls of the box. When the player moves more carefully, the balls stay in the box. How can I keep my balls inside the box? Here's a video and my the player script. Thank you!

https://gdl.space/sewaruvevu.cpp

lost hamlet
formal escarp
#

Hi. I am having 2 errors but im unsure on what im doing wrong or rather how to fix it 💀 i believe my code is okay? i am not seeing where i miss spelled something.

slender nymph
eternal falconBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

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

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

dusk musk
echo dove
#

Guys what is this....

slender nymph
#

you're trying to access something that is likely private

echo dove
#

I am trying to access a bool from another script

echo dove
slender nymph
#

show it

short hazel
#

No, it's not

echo dove
#

oh I think i forgot to save

#

mb

formal escarp
short hazel
#

Recommend sicking to naming conventions and naming that bool IsMoving (which makes it sound like a question)

#

And is in PascalCase (uppercase first letter for each word)

#

@echo dove

summer stump
echo dove
#

thx

#

Why should it be aquestion

#

I can make it Moving

#

because Moving == false;

#

or Moving == true;

#

Tells me the condition of moving or not

short hazel
#

It's the naming, so you know it's a bool

#

Is the player moving? IsPlayerMoving or IsMoving

#

And it looks better in if statements if (player.IsMoving) ...

echo dove
#

okay

#

Hi guys, my bullet is a prefab and I do not know how to give it commands from an object that isn't it just won't let me. That's why when the player stops (all stuff should be slowed down) the bullet doesn't. How can I fix this?

#

Pls help 😭

#

@echo dove

formal escarp
slender nymph
#

please actually read the instructions instead of skimming and assuming you know what it means

formal escarp
#

my first language is not english sorry.

slender nymph
#

well conveniently the microsoft website can be localized to a language you understand

cunning eagle
slender nymph
# formal escarp really?

yes scroll all the way to the bottom, you'll see the currently set language in the bottom left

slender nymph
echo dove
#

xd

slender nymph
formal escarp
eternal falconBOT
#

🧑‍🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

formal escarp
#

wait.

#

@slender nymph sorry but. installing the IDE like. uh. what is the IDE for

slender nymph
#

visual studio is your IDE. it's for writing code. you need to configure it to use it with unity. having a configured IDE will provide you with autocomplete and intellisense. it will also highlight your errors for you and provide syntax highlighting for unity types.
having it configured is a requirement for receiving programming help in this server

formal escarp
#

ooohh.

#

once its 100% installed, my code should look different right? well, rather my code Visual Studio itself?

#

NICE. I have it fully installed now.

echo dove
slender nymph
formal escarp
slender nymph
echo dove
#

Because I am not sure what is the problem here and what I should send

#

that is why I reached out here

ashen ferry
#

SceneManager.sceneLoaded += (_, _) => mainCamera = Camera.main; kekW does this meme of a syntax have a name wtf im doing here

wintry quarry
#

the (_, _) is usually more like (param1, param2)

#

but you're using discards _ instead of actual names since you're ignoring the parameters

cunning eagle
ashen ferry
#

aa cool

slender nymph
echo dove
#

oh okay

cunning eagle
rich adder
gray arrow
#

Hey guys, i'm trying to add bullet spread to my 2D top down shooter. however, the bullet keeps coming out at very peculiar angles when i shoot the gun. in the code below, which is the part that needs fixing, FirePoint is the point from which the bullet appears, and also is facing in the direction that the bullet needs to be fired in. can someone tell me whats wrong?

Vector3 BulletDirection = FirePoint.rotation.eulerAngles;

        if (Input.GetKey(KeyCode.Mouse1))
        {
            BulletDirection.z += Random.Range(-bulletSpreadADS, bulletSpreadADS);
        }
        else
        {
            BulletDirection.z += Random.Range(-bulletSpreadHipFire, bulletSpreadHipFire);
        }

        FirePoint.rotation = Quaternion.Euler(BulletDirection);

        GameObject bullet = Instantiate(bulletPrefab, FirePoint.position, FirePoint.rotation);
        Rigidbody2D rb2d = bullet.GetComponent<Rigidbody2D>();
        rb2d.AddForce(FirePoint.up * bulletForce, ForceMode2D.Impulse);
formal escarp
#

I FIXED ALL ERRORS! But i have a question. With all this + a physics material for making the player bouncy it should be able to jump right? I press spacebar and it does not jump.

echo dove
queen adder
cunning eagle
short hazel
cunning eagle
formal escarp
#

Can someone explain the "MissingComponentException: There is no 'SphereCollider"" error please? Sorry, i do not understand it.

unborn veldt
#

Hi! I'm generating a procedural world based on a seed. The world is subdivided in chunks. I need to generate a differend seed for every grid box, based on its x and y. How can I do that?

rich adder
echo dove
#

Anyways goodnight I hope someone could respond by that time

formal escarp
rich adder
formal escarp
#

oh. my bad.

rich adder
#

screenshot the error in the console

#

you should be able to expand to see more info

slender nymph
# unborn veldt Hi! I'm generating a procedural world based on a seed. The world is subdivided i...

a super simple way would be to add the X and Y together and hash that and add it to the regular seed. this will end up with some repeats though where 1,3 and 3,1 would have the same seed so you'd also need some other way to differentiate such as maybe also the hash of the angle from origin to the chunk.
or you could choose something else entirely, you just need to choose something that will be deterministic

tiny bloom
#

Hello everyone
I am not a beginner to C#, but please if someone can try to explain this whether it's in C# terms or simple unity terms
So the update method get calls once per frame
that means that if my pc is stuck to 60fps, that method will be called 60 times a second
so, if I have an array of 100 elements, and I loop it inside the Update method, that means each second I am looping 100*60 = 6000 elements
my question is, how does this work programmatically?
like each second, how does the CPU split the calls to those for loops? does it queue those loops and pass each one to a thread? what happens if one thread isn't done with its loop then time passes? does the thread skip that loop and jump to the next one assign to that second?
please refer me to any guides that discuss this, as I am not a game developer and I am trying to understand the effect of this on a large scale project

formal escarp
rich adder
formal escarp
#

ON PERSONAJE?

rich adder
#

yes

summer stump
formal escarp
#

OOHH

short hazel
#

Who reads error messages anyway :)

formal escarp
#

im going to rest. i cant even read that 💀

slender nymph
# tiny bloom Hello everyone I am not a beginner to C#, but please if someone can try to expla...

that loop will happen entirely on the same thread. unless you are setting up your code to run on multiple threads it will not do so. the unity API can also only be accessed from the main thread so unless you have an actual reason to use multiple threads, don't bother doing so.

your code will run sequentially so when update is called the loop runs to completion. no other code will be running during that time. then on the next frame the same thing happens

formal escarp
rich adder
#

hey errors usually tell you exactly whats wrong

formal escarp
#

i know. im just really tired.

rich adder
torpid herald
#

Why do you have to add L to the end of a long value, D to the end of a double number, and F in front of a float number? I was thinking it was for identification but wouldn't the keyword before the name of the variable already do that?

#

Sorry about the basic question, I tried to google it but it won't come up

summer stump
#

In an initializer, it is just a convention

timber tide
#

Yeah, it's not like you do Random.Range(0f, new float 1) so there needs to be some identifier

#

actually do you need to put f if you make it with two decimals

summer stump
timber tide
#

yeah true

short hazel
#

Default type for a decimal literal is double, so it will complain

summer stump
#

Just checked. It complained

#

Ah, yep SPR2 is right

short hazel
#

The postfixes are there so you don't need to cast the values to their correct type

timber tide
#

was working on some old opengl version and was having to type out 0f and some of its functions which I thought was funny

short hazel
#

12UL > (ulong)12

tulip tapir
#

Moin again, can someone tell how, how i get
Directory.GetFiles(Application.streamingAssetsPath + 4th Folder + Filename)
?
So how do i do this 4th folder thing?

swift crag
#

i don't know what this "4th folder" thing is at all

tulip tapir
tulip tapir
swift crag
#

well, iterate over the directories in the Application.streamingAssetPath directory and use the fourth one

swift crag
#

this returns an array of strings

#

you could actually just pick the fourth one directly

swift crag
#
foreach (var dir in Directory.GetDirectories(...))
#

but since it returns an array, you can just do Directory.GetDirectories(...)[3]

violet topaz
#

!code

eternal falconBOT
#
Posting code

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

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

violet topaz
tulip tapir
swift crag
#

this is a mess. what are you trying to accomplish here?

covert nest
#

hey everyone!

so im new to unity and im currently trying to get a simple input system for a 2D game. this script is basically supposed to use raycasting to detect when the mouse is hovering over a gameobject i have created known as a tile, and this object has a box collider on it.

however, the ray is not hitting it for some reason. i know its initiating the ray because the "RAYCASTING" debug log is sent, but nothing further than that is. any help?

void Update()
    {
        if (buildingBackend.getBuildMode())
        {
            RaycastHit hit;
            Ray ray = camera.ScreenPointToRay(Input.mousePosition);
            Debug.Log("RAYCASTING");
            Debug.DrawRay(Input.mousePosition, Vector3.forward);
            if (Physics.Raycast(ray, out hit))
            {
                Debug.Log("it raycast");
                if (hit.transform.parent.gameObject == Tiles)
                {
                    Debug.Log("ITS A TILE");
                    currentTile = hit.transform.gameObject;
                    if (previousTile == null)
                    {
                        Debug.Log("its the first tile!!");
                        currentTile.GetComponent<TileScript>().displayPrediction();
                    }
                    else if (currentTile != previousTile)
                    {
                        Debug.Log("its a NEW tile!!");
                        previousTile.GetComponent<TileScript>().hidePrediction();
                        previousTile = currentTile;
                        currentTile.GetComponent<TileScript>().displayPrediction();
                    }
                }
            }
        }
    }```
tulip tapir
covert nest
#

sorry if im interrupting something

swift crag
#

the actual raycast looks okay, assuming that camera is indeed the camera that's rendering right now

covert nest
#

oh the drawray was just me trying to see if the ray was shooting, forgot to remove it

#

yes it is

#

is this maybe some issue with layers?

plucky fractal
# violet topaz i have a issue with my game. the fire point is going out side the angle i assig...

Welcome to episode nine of this introduction to game development in Unity with C#.

In this episode we'll discuss the difference between global, object, and local space. We'll also look at how to parent, scale, and rotate objects through code.

Project files:
https://github.com/SebLague/Intro-to-Gamedev

If you'd like to support these videos, yo...

▶ Play video
swift crag
#

The default will hit every layer except "Ignore Raycast"

covert nest
#

hm. can you think of anything else that could be causing this??

plucky fractal
#

find a way to draw the ray where its actually pointing and see

covert nest
#

oh wait a second

swift crag
covert nest
#

does the Box Collider 2D component create a non-filled collider??

#

like, just the edge parts??

swift crag
#

you forgot to include Subfolder_2 in the GetFiles call

#

oh, you're trying to hit a 2D collider

#

3D raycasts don't care about 2D physics whatsoever

covert nest
#

im gonna try replacing the collider with a different type

#

see if that fixes it

swift crag
#

a 3D raycast will never hit a 2D collider

covert nest
#

eyy yes it fixed it

plucky fractal
#

I think my question was ment to be code-general, how can I move it there without double posting?

covert nest
#

was simply my silliness causing the issue

tulip tapir
swift crag
#

i mean to store the result of GetDirectories(...)[3] in a variable, and then use it on the next line

#

instead of trying to cram it all into one line

unreal imp
#

@polar acorn do you have an idea of how i could improve it?(so sorry for the ping 😭 ) and let me know if i wasnt clear in something 😦

ashen ferry
#

is there update method but for like always not only in play mode

timber tide
#

Like on the gui?

ashen ferry
#

it aint do nun

#
    {
        Debug.Log("test");
    }```
#

kekW should print no

timber tide
#

for editor stuff if that's what you're looking for

ashen ferry
#

executeAlways is what I needed not editor stuff wanted to set shader property so it would look right not only in play mode

#

ty

acoustic arch
#

my child object of the weapon parent rotating pivot point isnt set to the parent object

tulip tapir
frosty hound
acoustic arch
#

basically ive made what im trying to already in a different project but im making it again and i have it like the exact same but its not working

frosty hound
#

It's not exact if it's not behaving as before.

#

How pivots and rotations work is not a randomly determined outcome. That would make development impossible.

tulip tapir
#

can i
String = "Hello" - "llo";
to get "He"?

wintry quarry
#

but you can do cs string x = "hello"; string y = x.Replace("llo", ""); print(y); // prints "he"

silk night
#

what in the javascript is that syntax 😄

wintry quarry
#

which syntax?

tulip tapir
# wintry quarry no

can i
name = Directory.GetDirectories(Application.streamingAssetsPath + "Folder" + MoreFolder)[Number].GetDirectoryName();

silk night
wintry quarry
#

it's not real syntax

silk night
#

i know

wintry quarry
#

But it could be valid C# if string overrode the - operator

silk night
#

well it isnt until you plug it into javascript and god knows what the output will be

wintry quarry
#

(with using System.IO;)

tulip tapir
tulip tapir
#

does
GetDirectoryName()
work?

wintry quarry
#

why wouldn't it

tulip tapir
#

'string' does not contain a definition for 'GetDirectoryName' and no accessible extension method 'GetDirectoryName' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)

wintry quarry
#

Of course not

#

it's not part of the String class

#

look at the doc I linked

#

Path.GetDirectoryName

tulip tapir
#

but isnt a path a string?

wintry quarry
#

Path is its own class

#

there is a parameter in that function called path which is a string

tulip tapir
#

So
Name = Directory.GetDirectories(stringpath)[FolderPosition].GetDirectoryName();
?

wintry quarry
#

no

tulip tapir
#

why not? ^^

wintry quarry
#

because GetDirectoryName:

  • Is a static function on the Path class
  • doesn't make sense there
#

since you're doing GetDirectories it's already returning directory names for you

#

there's no need for GetDirectoryName

tulip tapir
#

So
Name = Name.GetDirectoryName();
?

wintry quarry
#

what is Name?

#

can you give an example of what you're trying to do?

#

The things you're writing are confusing and not consistent

tulip tapir
wintry quarry
#

I'm not sure I follow

#

give a concrete example

tulip tapir
#

So the Idea is:
GetDirectories[Position) --> Path
and then
Path - Path(exept Name)

wintry quarry
#

like if you have a folder:

Folder
  Subfolder1
  Subfolder2

What are you inputting and what are you trying to get out?

tulip tapir
wintry quarry
#

that's the input?

#

Or the output?

#

what do you already have and what are you trying to get?

#

ok and what information do you have that should result in you getting "Subfolder1" out?

ashen ferry
tulip tapir
wintry quarry
#

and you just want the last part?

tulip tapir
tulip tapir
#

Thats the Idea of
Name = Directory.GetDirectories()[FolderPosition].GetDirectoryName();

wintry quarry
#

you can do cs string folderName = new DirectoryInfo(Directory.GetDirectories()[FolderPosition]).Name;

#

or in general:

string folderName = new DirectoryInfo(fullPath).Name;```
acoustic arch
wintry quarry
violet topaz
wintry quarry
#

other than animator = GetComponent<Animator>(); but that doesn't affect anything - just gets a reference to the Animator

wintry quarry
# acoustic arch 32- 25

that's telling it to enter one of the animator states. The behavior of whether it will repeat or whatever will come down to how your state machine is set up

acoustic arch
#

weird

wintry quarry
wintry quarry
acoustic arch
wintry quarry
#

if there's nothing telling it to transition out of that state, it will stay there

wintry quarry
violet topaz
wintry quarry
#

just add a random rotation to firepoint's rotation and use that for the projectile.

#

no need to modify firepoint's rotation

tulip tapir
wintry quarry
# violet topaz thats what im trying to figure out

Try this:

        Quaternion rotation = firePoint.rotation * Quaternion.Euler(0, 0, Random.Range(-10, 10));
        Rigidbody2D bullet = Instantiate(bulletPrefab, firePoint.position, rotation);
        bullet.AddRelativeForce(Vector2.up * bulletForce, ForceMode2D.Impulse);```
#

note i made changes to all three lines, don't skip anything

wintry quarry
#

from this code?

#

what is this code supposed to be doing?

acoustic arch
tulip tapir
wintry quarry
wintry quarry
#

It shouldn't be in any folder that would result in a meta file being there

tulip tapir
wintry quarry
#

if you're reading it like this, it needs to go in the streaming assets folder

violet topaz
#

thanks for the help @wintry quarry

wintry quarry
# tulip tapir there it is

I guess the better question I have is - why are you accessing it based on a position in the directory rather than... say... name or something?

acoustic arch
#

cause its looping the attack state

#

once the trigger is active once

#

it needs a transition back to default

wintry quarry
tulip tapir
wintry quarry
#

I explained how to do that earlier

tulip tapir
tulip tapir
tulip tapir
wintry quarry
#

it will keep it. I'd do more like:

#
if (Name.EndsWith(".meta")) {
  Name = Path.GetFileNameWithoutExtension(Name);
}```
tulip tapir
wintry quarry
#

or :

if (Name.EndsWith(".meta")) {
  int extensionLength = ".meta".Length;
  Name = Name[0..^extensionLength];
}```
Does this work? I think it works 😉
tulip tapir
tulip tapir
wintry quarry
#

since the actual files will be there

tulip tapir
# wintry quarry can't you just skip the meta files entirely?

in the build, i will not need this line of code anymore, because the meta files will not be there anymore, but for developement in the editor, ill need this line. i fixed the mistakes now. But for some reason the functionality of my random function has changed xD
but, as a Pro-Programmer ... i dont ask why xD

swift crag
#

i am really, really, really getting the feeling that you're doing things the wrong way here

#

you keep asking questions about doing very strange things with file paths

wintry quarry
#

yeah - feels very XY problem to me

swift crag
#

isn't this one of the examples on the XY problem website

#

<n00b> How can I echo the last three characters in a filename?
<feline> If they're in a variable: echo ${foo: -3}
<feline> Why 3 characters? What do you REALLY want?
<feline> Do you want the extension?
<n00b> Yes.
<feline> There's no guarantee that every filename will have a three-letter extension,
<feline> so blindly grabbing three characters does not solve the problem.
<feline> echo ${foo##*.}

ok, not exactly, but,

wintry quarry
#

haha quite similar

ashen ferry
#

https://hatebin.com/whcoqziqhr what is this weird behaviour I have to move mouse around for it to run or it just stop altogether is it something to do with Time.deltaTime or update method or what how can I make it run properly in edit mode. It should fade in/out constantly as in the start

swift crag
#

The scene view will only update when it needs to

wintry quarry
swift crag
#

I don't think "Always Refresh" affects that

#

It looks like you're doing some smoothing on the colors. If you want to preview them outside of play mode, I'd just disable smoothing when not in play mode

ashen ferry
#

no I want to see that smoothing in edit mode too

#

im back at square one for a method which runs in edit mode like update does in play mode kekW

young warren
formal escarp
#

Hey guys i have a question. How can i make so my character can double jump? I have this code but it makes it so you can jump every time you want to.

eternal falconBOT
#
Posting code

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

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

formal escarp
#

wait do i
// code // ?

silk night
#

```

#

above and below

formal escarp
#

alr. thanks bro

silk night
#

add a "cs" behind the first to format it

formal escarp
#

like that?

silk night
#

like this

```cs
code
```

formal escarp
#

oh

swift crag
#

// indicates a comment in a lot of languages

#

so you will frequently see it used as a placeholder

formal escarp
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SaltoJugador : MonoBehaviour
{
    public LayerMask capaPiso;
    public float magnitudSalto;
    public SphereCollider col;
    private Rigidbody rb;

    void Awake()
    {
    }

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        col = GetComponent<SphereCollider>();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space) && EstaEnPiso())
        {
            rb.AddForce(Vector3.up * magnitudSalto, ForceMode.Impulse);
        }
    }

    private bool EstaEnPiso()
    {
        return Physics.CheckCapsule(col.bounds.center, new Vector3(col.bounds.center.x, col.bounds.min.y, col.bounds.center.z), col.radius * .9f, capaPiso);
    }
}
swift crag
#
if (florp) {
  // reticulate the splines!
}
formal escarp
#

thanks guys

formal escarp
silk night
#

As for your questions:

You raycast to the ground, if the raycast hits and is short enough for your character to (barely) touch ground you set a variable grounded to true and a counter to zero
if you jump grounded goes to false and counter goes up, you can jump while either grounded or counter < jump count

wintry quarry
formal escarp
#

So basically, a totally new script besides keeping this one 🤔 thanks.

wintry quarry
#

not really

formal escarp
#

i can do it on the same one?

wintry quarry
#

you just need to add a grounded check for the first part

wintry quarry
summer stump
wintry quarry
#

oh they do have a ground check

silk night
#

Oh yeah right

young warren
formal escarp
young warren
#

Maybe you opened the script outside of Unity. Look into it later. I don't want to derail the debugging

formal escarp
#

yeah i think that was it. lol. closed and opened and it is okay now.

silk night
#

So can you jump unlimited times now? Cause your script already checks if you are on ground

formal escarp
#

i can jump unlimited times.

silk night
#

is your SphereColider way bigger than your character?

#

or not positioned to its center

north kiln
eternal falconBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

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

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

formal escarp
#

not sure what happend on that screenshoot.

formal escarp
#

no. the collider seems fine to me.

summer stump
#

You go from the center and use the bounds and all that but you only really care about right below you
I would do a checksphere at the feet with a small radius or raycast

silk night
#

Oh i think I know what happens, the end part of the Physics.CheckCapsule is absolute, can you debug log us the col.bounds.center?

formal escarp
#

im unsure on how to do that let me google it rq

silk night
#

What it tries to do is check from center of the character collider to the bottom of it + some spare

silk night
#

above the return line

formal escarp
#

the ground check was line 23 right?

#

the "if input" blabla?

#

oh above the return one okay

acoustic arch
#

is there a way i can have the player's full sprite be shown in another menu, like even with all the attatched sprites in the child objects?

formal escarp
#

Here. I jumped 4 times.

verbal dome
acoustic arch
#

instantiate it in the menu and make it unable to move?

silk night
ashen ferry
#

if u want scene player to show up in ui view can u really clone that

formal escarp
#

it can bounce tho.

#

but i dont think that has anything to do with the infinite jump

verbal dome
acoustic arch
#

2D game btw

verbal dome
verbal dome
silk night
#

Ohhhh I know the problem now, your ground check detects your character as ground

verbal dome
#

Keep it on,or disable it and manually render it with camera.Render()

silk night
#

Because you are checking for the Default layer

#

Make your ground a new "Ground" layer

formal escarp
#

ooohh

silk night
#

and set that in the script for the ground check

verbal dome
formal escarp
#

man thanks a lot

silk night
#

Yes that should work

#

but you will detect ALL objects that have default as ground then

#

if you add a weapon and forget to change layer -> detects as ground

formal escarp
#

alright. thanks a lot man.

silk night
formal escarp
#

i think i figured it out

acoustic arch
#

anyone have tips for displaying my 2D character in the inventory, with all the child object sprites on it too

swift crag
#

one option would be a render texture: you'd make a camera that renders ONLY the player

#

you can render onto a texture, instead of the screen

#

and then just display that texture

acoustic arch
#

yeah that sounds alright

acoustic arch
silk night
#

Just call instantiate on an already existing object, it will copy it 1:1

acoustic arch
swift crag
# acoustic arch how would i do it?

Create a RenderTexture asset. Add a new camera that targets that render texture. Set its Culling Mask to only render the player's layer (you may need to create a new layer for the player here)

#

Then you can use the RenderTexture anywhere that a normal texture would be used, like an Image component

silk night
swift crag
#

it sounds like you want to display the player in a UI

#

in that case, you would need to be able to draw the player in an Image

acoustic arch
#

yes

swift crag
#

I guess you could try just gluing the entire player object into the inventory menu

acoustic arch
swift crag
swift crag
acoustic arch
#

and it will update as the players armor and other stuff changes on the player design?

silk night
#

yes

#

its like a live-stream of your character

swift crag
#

indeed

acoustic arch
#

oh cool

swift crag
#

Assuming all of the player's gear is being rendered by the camera.

#

You might just have a layer that all "entities" are on

#

not just the player

#

that would be close enough

acoustic arch
#

how do i use the RenderTexture

copper perch
acoustic arch
#

i can just select it inside where the player image in the inventory is

swift crag
#

oh, your'e right: it's not a sprite

#

use RawImage

acoustic arch
#

ah ok

swift crag
#

RawImage can't do everything an Image can (e.g. it can't do a sliced or filled image)

#

but it can use any texture

acoustic arch
#

just change the output?

copper perch
swift crag
elfin eagle
#

Hi so im trying to make it that if my player presses a key it enters a door. but the problem is when the person hits the key while inside the collison box it does not work, it only works if the player holds the key and then enters the Collison box. I want to make it that it only happens if they are inside the box.

swift crag
#

that method only gets invoked once: when you enter the trigger

eternal falconBOT
#
Posting code

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

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

swift crag
#

it's kind of like using GetKeyDown instead of GetKey

elfin eagle
#

ah ok I see.. but like I used OnTriggerStay2D but its still the same problem

#

Like im trying to have it when the person is inside the collison and when they hit the key then the operation happens

summer stump
swift crag
#

you used it when?

#

if the answer isn't "right now", go and change it and try it.

elfin eagle
swift crag
#

oh, this is 2D

#

i know that rigidbodies fall asleep...very aggressively

#

consider setting this to "Never Sleep" on the player

elfin eagle
#

ohhhhh that worked

#

dang rigidbody went to sleep 😦

#

thanks

swift crag
#

💤

#

I do very little 2D, but I found out about this while helping someone with a similar problem once

elfin eagle
#

yeah Im trying 2D out for fun

#

I like it so far

swift crag
#

Rigidbodies being able to sleep is a good thing -- it means the physics system can stop worrying about them until something hits them again

#

but it messes up trigger colliders, and there's generally just one player

#

not 300 of them

elfin eagle
#

i only intend on using on the player

swift crag
#

Less processing time.

#

The rigidbody is sleeping, so it doesn't need to have forces calculated

elfin eagle
#

alright thanks for the help again

swift crag
#

np!

tame grotto
#

Im making a 3d characters camera rotate based on the delta change of the camera, but at the start it has a huge shift and sometimes messes up the camera rotation

#

is there a way to set the cursor to the middle so it doesnt do that?

#

i set the cursor to locked in start but that doesnt seem to fix it

ashen ferry
#

I wonder is it possible to do anything so my lil rotating icon wouldnt freeze when loading scenes and running all the awakes/starts and such

teal viper
ashen ferry
#

how can you spread it over some time

#

I guess spawning in gameobjects little by little

teal viper
# ashen ferry how can you spread it over some time

You can make awake/start into coroutines or async methods.
Identify the scripts that take most time to initializes and spread them over several frames. If it's spawning objects, yield after a certain number of objects is spawned.

#

Could also maybe use the system time to yield after certain amount of time(like 10ms) or something

ashen ferry
#

Aaa cool ty

fluid mural
#

Trying to make it so camera rotates 90 degrees by pressing keys, and it works when I'm trying to turn right (d key). But whenever I press "a" the camera spins infinitely, what's wrong with my code? https://paste.ofcode.org/ZqMdFiMZbbsi2wVJ3kRXck

keen dew
verbal dome
#

Yeah, also MoveTowardsAngle instead of MoveTowards @fluid mural

#

So it loops around 360 degrees correctly

rare basin
#

hi, how can i create and work on an instance of a material? I have a shdaer and i want to have different texture for each unit slot

    private Material mat;
    
    private void Start()
    {
        mat = unitImageGrayScale.material;
        if(mat != null )
            mat.SetTexture("_MainTex", unitImage.mainTexture);
    }

this doesn't work its still not an instance

teal viper
rare basin
#

I am doing that, no?

#

getting's renderer (image) material

teal viper
#

Ah, if it's an image it's a different story. You can't mess with the material as it uses a different workflow. UI rendering is handled by the canvas.

#

If you just need to set a sprite for the Image component, it has a property for that. No need to access the material.

rare basin
#

I dont want to set an image

#

I have a Grayscale Shader that takes Texture2D

#

and i want to get the texture from the sprite of the Image and assign it to the shader's material instance

#

because right now it changes to the same texture for all images :/

#

and each slow has different unit assigned

#

okay nvm _MainText automatically gets it from the image

#

solvd

queen adder
#

does unity have builtin methods for manipulating sprites? like flip horizontal/vertically?

teal viper
queen adder
timber tide
#

it's on the sprite renderer

queen adder
#

ah yea, me dont wanna use that :>

#

so i was curious if there's something like SpriteUtility something

timber tide
#

yeah im not too sure how it works on the sprite renderer

#

but if it's flipping the UVs, I guess there's some extra logic to keep it instance independent

queen adder
#

actually theres an actual spriteutility class lol

timber tide
#

probably modifies the mesh UVs or something

queen adder
#

just not useful for this though

flint pilot
#

Good evening everyone, sorry for this question, I would need some help regarding a mini project but since this is the first time I put my hand to code for VR I would like to know if someone could write the code for me so I can reverse engineer. I need to create some basic interactions for VR but without using external plugins, these interactions I need to take apart the bolts of a car and change the tire. If anyone can help me out I would really appreciate it.

keen dew
#

That's a really big ask. I doubt you'll find anyone willing to do that.

#

You'd have more luck if you tried it yourself and then asked specific things when you get stuck

winter shore
#

Hello, in if, I wanted to make sure you must have these conditions. I used "&&" for that, but does not work. Is there another way to address this issue ?

rare basin
#

why do you want to do it on Sprite type

#

Sprites themself don't have "flip" properties

spare umbra
#

Dash isn't consistent! I'm calling the Dash function on PlayerInput script. How can I call it in FixedUpdate (because this is physics based)

    private IEnumerator DashCoroutine()
    {
        canMove = false;
        isDashing = true;
        rb.velocity = direction * dashSpeed;
        yield return new WaitForSeconds(dashDuration);
        rb.velocity = Vector2.zero;
        isDashing = false;
        canMove = true;
    }```
north kiln
eternal falconBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

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

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

north kiln
#

Then note that SetActive is not a condition. The function returns nothing

winter shore
spare umbra
gaunt ice
#

the unit of velocity is already m/s, if you multiple it with time it will becomes m, ie displacement

winter shore
#

I'm in Mac.

north kiln
#

Choose the IDE that you're using

#

there are 5 options

winter shore
north kiln
#

what condition, there is no condition, the method returns nothing. Did you mean to use .activeInHierarchy or similar?

winter shore
#

Yes, exactly. In Hierarchy.

true thorn
#

hi guys! I am trying to spawn my players in random places but it seems I have some issues with Random.Range and I don't quite understand why my editor is not happy with it. transform.position = new Vector2(Random.Range(positionRangeSpawn,-positionRangeSpawn), Random.Range(positionRangeSpawn, -positionRangeSpawn));

#

I keep getting this "'Random' is an ambiguous reference between 'UnityEngine.Random' and 'System.Random'"

true thorn
north kiln
#

Are you using the System namespace?

true thorn
#

yep

north kiln
#

What needs it?

#

If nothing, remove it.

true thorn
#

oh

north kiln
#

If you need it, specify the namespace you're using either via an alias, or when you access the type

true thorn
#

got it

#

thanks

vernal sequoia
#

I have a question. If I define the boundaries of an object in the start method, through bounds, and then bind these boundaries to a certain point, which will take the rotation and position of the object on which the script hangs, will the boundaries be superimposed on the object?
Because if you run an update in the method, then the boundaries will not be bounds, they will not follow the object, but will be, as it were, like a cube described around the figure, which does not change its rotation, which means that it will not actually be superimposed on the object, along its boundaries.

#

I just have a cube for which I need to constantly know the positions of the upper corners, and if I use bounds, then during rotation the points are not in the right place

#

Can I define bounds once in the start method and then bind them to a point?

tender stag
#

how do i make this run once?

#

its in update

gaunt ice
#

use an additional bool to guard

verbal dome
#

I mean when the durableItem.Durability gets changed

gaunt ice
#

and you can write as follow:

if(x is A a)
verbal dome
#

Btw you can type if(item is IDurable durableItem)

#

Yeah that

tender stag
#

like gun script

#

so the item doesnt know which slot its in

#

only the slot knows what item its holding

tender stag
#

and in my hotbar manager i handle like enabling the correct game objects in players hands

#

and OnEnable i cast the item

#

and when i shoot i just do this

gaunt ice
#

wait you check durability of holding item in update? i think you can change it to event driven

verbal dome
#

Thats what im saying

tender stag
#

i maybe could do that

gaunt ice
#

yes

tender stag
#

but then what about items for example which have the durability decay?

#

like food items

#

over time the durability will decrease

gaunt ice
#

timer in update

tender stag
#

how does it know which slot to update?

#

durability

#

items do not know about slots

verbal dome
#

Sounds like you need to redesign your item system a bit

tender stag
gaunt ice
#

you can update all registered items in slot (btw not sure your code structure), if the item is broken or expired then deregister it from your slot

thick goblet
#

I have a cube with 3 lanes similar to subway surfers. When I click A I want the player to move to the left lane and D for the player to switch to the right lane. My script somewhat works except sometimes my input doesn't register and it just sometimes glitches and doesn't respond how I want it to. What's the problem? https://hatebin.com/mrgynyiqfr

languid spire