#💻┃code-beginner

1 messages · Page 572 of 1

north kiln
#

The resource I linked tells you how to operate on them

#

There is never a need to convert to string, unless you want to display something in an interface

blissful yew
#

I was actually talking about nonbinary, but I guess there's not too much reason to do that

regal kettle
#

yall know how you can edit a null value in unity rather than assign a value in the script itself right

#

how do you do that with integers

#

nvm i found it tis serialize field

rich ice
rich ice
regal kettle
#

ohhh right public

#

silly me

rigid tiger
sharp sigil
#

i got a question guys
why does this not work?
if (Input.GetKeyDown(KeyCode.Q))
{
rb.velocity = transform.forward *dashForce;
}
my character just freezes in the air for a moment when i press it

#

and when i increase the dash force i just teleport forward

#

the same happens when i use
rb.AddForce(transform.forward * dashForce, ForceMode.Impulse);

rich ice
#

!code

eternal falconBOT
rich ice
queen adder
sharp sigil
#

aight lemme try

#

its always 0

#

even when i dash

rich ice
#

is the position locked? it could also be set to kinematic

frosty hound
#

Where and how are you assigning a value to dashForce

sharp sigil
#

oh

#

i assign dashforce though the inspector

rich ice
#

freeze position should be false on all axis and is kinematic should be false

rich ice
sharp sigil
#

yes its 1000 rn

sharp sigil
rich ice
#

can you send the full script?

#

!code

eternal falconBOT
queen adder
sharp sigil
#

i cant it says that i need nitro

#

i mean the position that i teleport to changes based on the value of dashforce

rich ice
eternal falconBOT
queen adder
#

Just print both of it, check if the value is different

rich ice
#

use one of the paste sites

sharp sigil
#

so i print rb.velocity and transform.forward?

#

transform.forward*dashforce changes but velocity is still 0

#

im pretty sure i used the same method on a previous project and it worked fine

slate haven
sharp sigil
#

aight lemme try

slate haven
#

rb.AddForce(transform.forward * dashForce, ForceMode.Impulse);
Also this

#

anything related to physics goes inside FixedUpdate()

slate haven
# sharp sigil aight lemme try

Also for physics based calculations, use Time.fixedDeltaTime instead of Time.deltaTime but make sure to call in fixedUpdate()

sharp sigil
#

what exactly do i multiply with deltatime

slate haven
sharp sigil
#

aight ty imma try that

slate haven
#

Anything you are applying to the object with physics

#

Multiply it with that

fossil tree
#

hello i have a problem i try to add a Coyote Time and a Jump Buffering but now my character can double jump if i spam space https://medal.tv/fr/games/requested/clips/jt4A5fUeWNTfh3BvI?invite=cr-MSx6Q1EsMjUxMjMyMDQ3LA
this is my character controller code: https://pastecode.io/s/iop2q9ak

Regarde Requested et des millions d'autres vidéos Requested sur Medal, la plus grande plateforme de clips vidéo.

▶ Play video
sharp sigil
#

so im calling it in the fixedupdate and it doesent seem to do danyhitng now

#

not even teleport

slate haven
sharp sigil
#
private void FixedUpdate()
{
    if (Input.GetKeyDown(KeyCode.Q))
    {
        rb.velocity = new Vector3(rb.velocity.x, rb.velocity.y, rb.velocity.z * dashForce*Time.deltaTime);
    }
}

like thuis

sharp sigil
#

oh

slate haven
#

rb.velocity * Time.fixedDeltaTime

#

I meant this

#

Multiply the final product of whatever physics u calculated, with the delta time

slate haven
sharp sigil
#

idk

#

bro i feel so stupid rn

slate haven
#

Its okay, everyone is dumb.. We just gotta do it better

sharp sigil
#

lmfao

slate haven
#

But what I suspect is, this might not even be the main issue, But atleast do this then lets see if it works

sharp sigil
#

just this in fixedupdate?

languid spire
#

deltaTime in FixedUpdate is the same a fixedDeltaTime.
The question is why are you reading Input in FixedUpdate. That should be in Update

slate haven
slate haven
sharp sigil
#

i dont understand how do iget the input and then apply it in the fixed update

#

with a void?

languid spire
#

no, with a bool

sharp sigil
#

makes sense

slate haven
languid spire
#

how are you going to sync FixedUpdate with an event?

slate haven
#

use events whenever input is retrieved, store them somewhere, maybe the direction or anything.

slate haven
sharp sigil
#

so i set isdashing true in update and i used the thing with velocity in a if statement in fixedupdate

languid spire
#

no

sharp sigil
#

it still does nothing

#

and after that i disable isdahing

slate haven
sharp sigil
#

i tried ye

slate haven
#

what does it show in debug

sharp sigil
#

by debug i mean go into play mode and press q

languid spire
#
bool isPressed=false;
void Update() { if (Input.GetKeyDown(KeyCode.Q)) isPressed=true; }
void FixedUpdate() {
   if (isPressed) {
      isPressed=false;
      // Do other stuff
   }
}
#

@sharp sigil

sharp sigil
#

ye i did that

#

it gets my input but nothing happens

#

i printed something into the log in the if statement

languid spire
#

so you need to add some debugging

sharp sigil
#

im thinking about making teleportation into a feature man

slate haven
#

break the problem into each step

#

try solving 1 at a time

#

take a paper and a pen, note down whats the problem?
You cannot solve it ofc, so debug, ask questions to the program.. maybe ask a duck about your problem..

it will help a lot

queen adder
#
   private float Speed = 8f;

    [SerializeField]private Vector2 TargetPosition;


    // Update is called once per frame
    void FixedUpdate()
    {
        if (TargetPosition == null || new Vector2(transform.position.x, transform.position.y) == TargetPosition) {
            TargetPosition = LogicManager.Instance.GetRandomCanvasPosition();
            Debug.Log("Searching");
        } else {
            transform.position = Vector3.MoveTowards(transform.position, new Vector3(TargetPosition.x, TargetPosition.y, transform.position.z), Speed);
            Debug.Log("Moving");
        }
    }

I have a Objects that just should moving around the canvas, it works for 1-2 cycles, after that it stop moving. It still prints out "Moving", But the valus doesnt match. The Screenshot was taken after it stoped moving. Is something wrong with my moveTowards Code?

#
    public RectTransform MyCanvas;


    public Vector2 GetRandomCanvasPosition() {

        float RandomWidth = Random.Range(-MyCanvas.rect.width/2, MyCanvas.rect.width/2);
        float RandomHeight = Random.Range(-MyCanvas.rect.height/2, MyCanvas.rect.height/2);

        Debug.Log(new Vector2(RandomWidth,RandomHeight));
        return new Vector2(RandomWidth,RandomHeight);
    }
sharp sigil
#

you think my project is the problem?

#

once in my project the light flickered all the time

#

and i switched projects and it didnt happen anymore

rich ice
#

would help if you sent the !code

eternal falconBOT
fossil tree
rich ice
#

updatE: nvm

#

yeah my bad, completely missed that

sharp sigil
#

forget it im giving up

slate haven
queen adder
slate haven
#

@queen adder also try this Vector2.Distance(new Vector2(transform.position.x, transform.position.y), TargetPosition) < 0.01f)

rich ice
slate haven
rich ice
fossil tree
#

mb

slate haven
fossil tree
slate haven
#

okay

#

so you dont want the player to double jump?

fossil tree
#

yes

slate haven
#

what if u just press space one time? does it double jump too

queen adder
slate haven
# fossil tree i make a clip of it

what i understand is, if u keep holding space, it makes ur character stay more in the air, right? but in your case it is making it double jump

fossil tree
slate haven
slate haven
fossil tree
slate haven
# fossil tree yes

In that case you can pause the input system for a while till the jump completes, make a coroutine, and make the elapsedTime get decreased until it reaches the jumpTotalTime. Then the input system can read values again

#

I mean, make something, make a function, that stops reading the input values from the keyboard till the jump completes and it is grounded

fossil tree
slate haven
fossil tree
slate haven
fossil tree
#

instead of the add force ?

#

that dont change anything

#

i can always do a double jump with spamming

#

but now the coyote time is more smooth i think

slate haven
#

i mean ofc this wouldn't solve your problem

#

i just noticed an area of improvement

#

otherwise i never have done buffer jump or coyote, so maybe i wont be able to help much in that sorry

fossil tree
#

i found the problem it was because my scene is really small so i need to reduce the time of the coyote time and of the jump buffering

whole lark
#

hi, i am pretty new to unity and all that stuff and i am trying do make a simple script that helps me open and close a inventory, that i copyed from an other asset. i really tryed a lot but im not finding a solution for it. so i am having a canvas that i want to be able to close and open with a button, but always when I try its just not opening xd does someone know what the problem might be?

wintry quarry
cosmic dagger
eternal falconBOT
whole lark
lethal smelt
reef bluff
#

how do I set the lightmodetag of a shader graph in urp?

#

by default its none in the generated shader and I can't find a way to change it

#

you can't edit the generated shader code either it just reverts

sharp abyss
#

https://pastebin.com/rvAmsfKv
I have this script for my stickman ragdoll enemies. But it doesnt work.I mean doesnt get the triggers from "weapon1 hold" gameobject.I want weapons to collide so I wanted to keep them as colliders but oncollisionenter2d doesnt work if gameobject doesnt have a rigidbody and when I put a rigidbody that is not kinematic, everything messes up.When I put a kinematic one, I prevnt collisions between weapons and thats not something I want. So I added a trigger collider to "weapon1 hold" and a normal collider on "weapon 1". Then, changed oncollisionenter2d to trigger enter.But it never triggers.

this photo is from when I equip a weapon.

wintry quarry
serene barn
#

hello I have a problem that when i jump i keep sort of floating and go down really slow is there any quick solution i am using rigidbody for my movement?

rocky canyon
#

u probably have some type of
movement code influencing it..
maybe a collider or two interacting w/ each other
ur drag value is too high..

#

or not enuff gravity * u can always crank up the gravity settings (but this will affect everything).. or add a bit extra negative forces to ur player when not grounded..

#

oh yea.. check ur grounded state ^ make sure its working as it should as well

serene barn
#

thanks!

sharp abyss
tulip nimbus
#
   [SerializeField] float Sens;
   public Transform camtransform;

   float xRot = 0f;
   public float xMouse;
   public float yMouse;

   private void Start()
   {
       Cursor.lockState = CursorLockMode.Locked;
       Sens = 180f;
   }

   void Update()
   {
       
       xMouse = Input.GetAxis("Mouse X") * Sens * Time.smoothDeltaTime;
       yMouse = Input.GetAxis("Mouse Y") * Sens * Time.smoothDeltaTime;

       xRot -= yMouse;
       xRot = Mathf.Clamp(xRot, -90f, 90f);

       
       transform.localRotation = Quaternion.Euler(xRot, 0, 0);
       camtransform.Rotate(Vector3.up * xMouse);

   }

So i have this problem in all my first person FPS games where my camera position and rotation is not calculated properly. When in Playmode my Camera stutters, randomly accelerates the sensitivity, and skipps multiple frames when looking at certain objects. How can i fix this, and what is there to know when making a camera controller?

sharp abyss
solid jay
#

I have two objects I wann rotate the same amount, I input the same degrees but they rotate diffrently.

Code to rotate the Obejcts:

transform.Rotate(new Vector3(0, yRotation, 0), Space.Self);
Camera.Rotate(new Vector3(0, yRotation, 0), Space.Self);
sharp abyss
#

is the y values on inspector when you rotate, same on both?

solid jay
#

no, but it should be, since im rotating by the same amount

sharp abyss
#

do they have rigidbodies?

solid jay
#

one does but the rotation is locked

sharp abyss
#
Camera.Rotate(new Vector3(0, yRotation, 0), Space.World);

try this

burnt vapor
#

Also, log yRotation, see if it matches

#

Rotate differently as in different rotational speeds?

solid jay
solid jay
burnt vapor
#

I would not know. You haven't shared anything but two lines of code

#

Are these two lines after eachother?

solid jay
solid jay
solid jay
# burnt vapor I would not know. You haven't shared anything but two lines of code

this is the function

void TurnCamera()
    {
        /*
        yRotation += Input.GetAxisRaw("Mouse X") * Time.deltaTime * xSens;
        xRotation -= Input.GetAxisRaw("Mouse Y") * Time.deltaTime * ySens;
        xRotation = Mathf.Clamp(xRotation, -90, 90);

        transform.rotation = Quaternion.Euler(currentPlayerRotationOffset.x, yRotation,currentPlayerRotationOffset.z);
        Camera.localRotation = Quaternion.Euler(xRotation, yRotation, transform.rotation.z);
        */
        
        
        //xCamRotation -= Input.GetAxisRaw("Mouse Y") * Time.deltaTime * ySens;
        //xCamRotation = Mathf.Clamp(xCamRotation, -90, 90);
        
        yRotation = transform.rotation.y + Input.GetAxisRaw("Mouse X") * Time.deltaTime * xSens - transform.rotation.y;
        
        transform.Rotate(new Vector3(0, yRotation, 0), Space.World);
        Camera.Rotate(new Vector3(0, yRotation, 0), Space.World);

        Debug.Log("Y Rotation: " + yRotation);
    }
sharp abyss
#

whats the purpose actually?

burnt vapor
solid jay
burnt vapor
#

Is the camera a child component of anything?

#

And do these components have scaling of any sort?

solid jay
solid jay
burnt vapor
#

Well idk. If I were you I'd rotate the transform and then set the camera's rotation to match the transform's rotation

#

Doing it separate can lead to issues in general

#

I don't see why it's broken here, but I would just synchronize it like that regardless

solid jay
#

but then the cam doesnt rotate around its local y axis and I need that

celest jacinth
#

the only way to make a capsule collider stay fixed in one side (only increase or decrease height from one side) is to use an offset, right?

rocky canyon
#

then it wouldn't be a capsule anymore.. but a weird metaball or somethin

silk verge
#

What do i need to do, when I want one animation to be played on S or D (Walking animation

#

Tried this but this dont work (first one)

rich ice
#

i really wish there was a !screenshot command wobblepensive

slender nymph
#

you mean like !screenshots

#

wait did that get removed

#

!screenshots

eternal falconBOT
#

mad No

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

rich ice
slender nymph
#

there it is

rich ice
#

o, good to know

slender nymph
eternal falconBOT
echo copper
#

guys, hello. how to get an angular velocity. like... i use this code to move character on slopes:

#
rb.velocity += transform.TransformDirection(new Vector3(Xlimit * axis, 0, 0) * Time.deltaTime);
#

and how to get this Xlimit if z rotation is not 0 (that code moves body based on it's z rotation)

#

anyone?

sharp wyvern
#

'm having trpouble understanding the Q

echo copper
#

Q? wdym?

sharp wyvern
#

you question, I cannot understand what you are asking.

#

you mention angular veloicty, but dont talk about rotataions.. just linear velocity.. not sure what XLimit is, nor where the z rotation comes in

#

do you want to rotate something?

echo copper
#

and i want to check if this velocity.x is higher or smt like that

#

and as i use transformDirection, my velocity would not be like (Xlimit * axis, 0, 0)

#

should i describe it clearly?

gleaming carbon
#

just stared using untiy on my home computer instead of the ones at my collage, however visual studio wont recognize

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

or

MonoBehaviour

Can anyone help?

sharp abyss
#

check if you chose unity on installer

rich ice
#

!IDE

eternal falconBOT
gleaming carbon
#

im not too sure on what my issue is

slate haven
#

If i have a 3D plane in unity of some scale... I want to know what is the width and height of it, how can I calculate?

sharp wyvern
gleaming carbon
#

here is the basic code, but its just not compiling properly or recognizing anything

slate haven
eternal falconBOT
burnt vapor
gleaming carbon
#

lol

#

yeah i already done that

burnt vapor
#

Also, is VS the external editor used?

gleaming carbon
burnt vapor
#

Alternatively, you might want to regenerate the project files

gleaming carbon
#

already have

burnt vapor
# gleaming carbon no?

This is a step in the manual installation of VS to use Unity. If you didn't do this then that will be the issue most likely

slender nymph
burnt vapor
#

Considering there are only three steps, and it worked for everybody so far, I suggest you try again

gleaming carbon
#

well ive already done them prior to joining this server

burnt vapor
#

That's fine, but we require users to have their editor set up regardless of the problem

#

Not just to fix the problem either. You should have a configured editor to improve your development experience, and we want to ensure you have that

echo copper
# echo copper should i describe it clearly?

ok. I have velocity (a, 0, 0) and rotation (0, 0, 0) on the first image. And i have TRANSFORMDIRECTION velocity (a, 0, 0) and rotation (0, 0, 45). how to find this a in second image outside of TRANSFORMDIRECTION? like not from variable a, but from velocity.

slender nymph
#

since you appear to be manually assigning velocity anyway, just keep track of what the current velocity would be if you were travelling along flat ground, and just rotate that to use for assigning the rb.velocity. then you don't need to do extra math to dtermine the linear speed

echo copper
#

but... what math would i do to find this... velocity?

slender nymph
#

so you just completely ignored what i just said or what?

echo copper
#

here is a code where i want to find this... velocity:

if (transform.TransformDirection(rb.velocity).x > 0)
    rb.velocity -= transform.TransformDirection((new Vector3(Xlimit, 0, 0)*Time.deltaTime));
if (transform.TransformDirection(rb.velocity).x < 0)
    rb.velocity += transform.TransformDirection((new Vector3(Xlimit, 0, 0) * Time.deltaTime));  
if (transform.TransformDirection(rb.velocity).x > 15 && transform.TransformDirection(rb.velocity).x < -15) { }
    rb.velocity = transform.TransformDirection(new Vector3(0, rb.velocity.y, rb.velocity.z));
slender nymph
#

i am telling you to change how you go about this, not to do something specific with your existing code. because frankly that's horrible

echo copper
#

okay...

slender nymph
#

instead of rotating the velocity increase before adding it to the current velocity, you instead just have a flat velocity that you increase then rotate that before applying it to the rigidbody. then your max speed is right there in your flat velocity

timber tide
#

setting velocity seems like extra work if you're doing a sanic game

#

cause you're going to have to manage the deacceleration on collision

echo copper
#

no, i use rigidbody, so my Sonic stops automatically on collision

#

or... it's not as i need to do..?

timber tide
#

and setting velocity overrides friction making physics material unusable

slate haven
#

I have Plane's width and height, now I want to decide how many cells must be in that plane, suppose 120 cells I want, so How do I calculate the no. of rows and no. of columns required? (Grid System)

timber tide
swift crag
timber tide
#

yes but the forces are still being applied

swift crag
#

you don't go through it or catapult into the air

timber tide
#

you can't just change your direction instantly when ramming into a wall at a speed

echo copper
tawny grove
#

okay i thought i understood how transform positions work but apparently not. Why is the room being spawned at such an offset if the transform pointer is at the middle of it, and is being instantiated with no offsets?
(image 1 is the room, image 2 is the spawner, image 3 is the code spawning the room, image 4 is the result)

#

it was working fine until i increased the size of the room, and i thought i made sure the transform position was still correct

#

the script is inside the spawner btw

#

template.structures[3] is just the room prefab

swift crag
#

make sure that you have your scene view set to "Pivot" and not "Center" -- check the top left of the corner

tawny grove
#

oh my god why did it set it back to center

#

thank you

swift crag
#

there are two modes: Pivot and Funny Joke

#

(Z is the shortcut; you might've hit it)

tawny grove
#

oh lol, i need to disable that

#

what is even the point of using center?

swift crag
#

It's useful in a few cases

#

notably, when you have many objects selected, it lets you rotate them around the center of their combined bounding box

#

instead of rotating individual objects in-place

#

same goes for scaling

tawny grove
#

that is interesting, thanks!

#

is there a easy way using tile maps to move the tiles beyond the move tool?

swift crag
#

you should be able to select many tiles..

#

I'm a bit of an novice with the tilemap system though

silk verge
#

Anyone knows why animation that require 2 Keys pressed at same time doesnt work?

slender nymph
#

show code

silk verge
# slender nymph show code

else if ((Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.A)) || (Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.D)))
{
animator.SetInteger("Animacie", 15);
}

#

in animator its set up correctly, from primary to this equals 15 from this to primary equals 0

slender nymph
#

have you actually confirmed the condition is true? also !code

eternal falconBOT
slender nymph
#

note that if whatever if statement precedes this one is true this one won't be evaluated

slender nymph
# silk verge how? 😭

literally the first thing you should have learned in unity is how to log something to the console. so maybe consider doing that?

lethal smelt
silk verge
#

oh this xd

#

mb

slender nymph
lethal smelt
#

yea lol I just gave example

silk verge
#

cuz i m trying to do mk character he jumps and walks but when u play W (jump) and D or A (Walk) all at once he just walks in the air

#

i thought i can fix it like this but idk

celest flax
#

If I have a list of game objects, and I am referencing the positions of those game objects several times in code, would it me more efficient to make a new array/list of vectors containing the positions of the objects, and reference those instead?

wintry quarry
#

Is this question in response to an actual performance problem you're seeing, or just exploratory premature optimization?

celest flax
wintry quarry
#

If you're doing something in the name of performance for your assignment you should be prepared to demonstrate with data that it actually helped.

swift crag
#

Accessing a property like .position involves a call into native unity code, so it's certainly possible that it'd be faster to store it and re-use it if it's being accessed many many times

#

Also, if you do wind up profiling this -- don't use the Deep Profile option. It will give you very skewed results

grand snow
#

so as others say there isnt gonna be a benefit if you want to be looking at the Transforms actual positions

swift crag
#

It'd only be valid if you were certain that the transforms weren't moving (along with their parents!)

grand snow
swift crag
#

You can use the Profiler methods to view timings in the profiler window

grand snow
#

oh yea i forgot about those

quick pollen
#

is there a way to use Vector3.MoveTowards with root motion?

#

transform.position = Vector3.MoveTowards(transform.position, currentTarget.transform.position, Time.deltaTime * correctionSpeed);

#

I am trying to make it so the player moves closer to the enemy when it's about to attack but is very slightly out of range, but changing transform.position directly causes issues, due to me also using root motion

strong wren
quick pollen
#

turning off root motion does fix the issue, so I can only assume that its that which is causing problems

#

oh shit

quick pollen
#

now I only have some mathematical things to deal with

#

thank you very much!

#

ah, one problem

#

it seems to... turn off root motion now?

twin pulsar
#

Hmm... I was replacing the Input Manager with the Input System, and I decided to try to do a lightweight replacement with this code:

if (_controls.DungeonEscape.Attack.IsPressed() && isGrounded)
{
_playerAnimation.SetAttack();
}

Except, when I do that, the attack fires off twice for some reason. I've replaced my code with catching the event for the button press being performed, but I'm curious as to why it worked this way.

wintry quarry
#

IsPressed is like GetButton
WasPressedThisFrame is like GetButtonDown

twin pulsar
#

Ah, that does fix it. Thank you.

quick pollen
#
        if(correcting){
            Debug.Log("correcting");
            float distance = Vector3.Distance(transform.position, currentTargetPosition);
            if(distance > maxDistance)
                transform.position = Vector3.MoveTowards(transform.position, currentTargetPosition, Time.deltaTime * correctionSpeed);
            else if(distance < minDistance)
                transform.position = Vector3.MoveTowards(transform.position, currentTargetPosition, -Time.deltaTime * correctionSpeed);
            else correcting = false;
        }  
    }```
#

it does work, it does the correction

#

but it just completely turns off root motion?

quick pollen
#

I tried animator.applyRootMotion = true; but it makes no difference

swift crag
#

If you have a component with an OnAnimatorMove method, the animator will no longer apply root motion on its own

quick pollen
#

animator.ApplyBuiltinRootMotion(); worked

#

I just did it

swift crag
#

ah, there you go

quick pollen
#

thank you tho, thats good to know!

#

seems to work well!!

#

cause, you know, otherwise you might miss a hit because you were a few units off

arctic shore
#

hello any idea why my enemy is not moving he should move left between my posts and i dont understand why he is isnt

#

sorry i meant this code ```using UnityEngine;

public class PatrolController : MonoBehaviour
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
[Header ("Patrol points")]
public Transform rightEdge;
public Transform leftEdge;

[Header("Enemy")]
public Transform enemy;

[Header("Movement")]
public float speed;
private Vector3 initScale;
void Start()
{
    initScale = enemy.localScale;
}

// Update is called once per frame
void Update()
{
    MoveInDirection(1);
}

private void MoveInDirection(int direction)
{
    enemy.localScale = new Vector3(Mathf.Abs(initScale.x) * direction, initScale.y, initScale.z);
    enemy.position = new Vector3(enemy.position.x + Time.deltaTime * direction * speed,enemy.position.y,enemy.position.z);
}

}

tawny shell
#

Hello, i am currently working on a lil project and i am struggling with displaying the good layers of my sprite

swift crag
tawny shell
#

I tried to handle the layers i wanted to display with this script:

public class LayersHandler : MonoBehaviourPunCallbacks
{
    private Dictionary<string,GameObject[]> _allLayers = new();
    [SerializeField] [CanBeNull] private GameObject childToEquip = null;
    [SerializeField] [CanBeNull] private GameObject parentToUnequip = null;
    
    void Start()
    {
        // loads all layers
        GameObject group, layer;
        for (int i = 0; i < gameObject.transform.childCount; i++) 
        {
            group = gameObject.transform.GetChild(i).gameObject;
            
            GameObject[] layers = new GameObject[group.transform.childCount];
            for (int j = 0; j < group.transform.childCount; j++) 
            {
                debug += " | " + group.transform.GetChild(j).gameObject.name + "\n";
                layer = group.transform.GetChild(j).gameObject;
                layer.SetActive(false);
                layers[j] = layer; 
            }
            
            _allLayers.Add(group.name, layers);
        }

    }
    
    void Unequip(string parentName)
    {
        foreach (GameObject layer in _allLayers[parentName]) layer.SetActive(false);
    }
    
    void Equip(GameObject equipement)
    {
        // Equipements data
        string[] inputs = equipement.name.Split('_');
        Unequip(inputs[0]);
        equipement.SetActive(true);
    }
    
    // Update is called once per frame
    void Update()
    {
        if (childToEquip != null)
        {
            Equip(childToEquip);
            childToEquip = null;
        }
        if (parentToUnequip != null)
        {
            Unequip(parentToUnequip.name);
            parentToUnequip = null;
        }
    }
}
arctic shore
tawny shell
#

I wanted to drag and drop the gameobjects i wanted to equip or unequip here

#

the problem is that it should have equiped it and set itself to None

#

like that but it does not

#

thanks in advance

crimson pike
#

UI Toolkit and legacy UI can both be used in the same project right

arctic shore
#

why?

swift crag
#

Ah, the animator was probably controlling the position of the enemy

arctic shore
#

but that animation is was idle

swift crag
#

As long as it sets the enemy’s position, it will override whatever you try to do to the enemy

arctic shore
#

nothing there

swift crag
#

This happens if any animation sets the position

#

I usually set up my characters with a root object that I parent the visual to

#

(And the visual is what has the animator)

arctic shore
#

how do i know if animation set postion beacuse in animation i only change sprites

swift crag
#

You'd need to look at every animation that the Animator is using

#

(which will be all of the animations in this list)

arctic shore
#

yes i know but how to check if they change postion beacuse my only animation that was running was idle

grand snow
#

if you have write defaults on (for an animation state) and another state set position, the other states will change it back to the "default"

swift crag
#

as long as any motion on any layer with a non-zero weight sets that property, the animator will never stop writing to that property

arctic shore
#

i dont understand i didnt write anything there
so what to do

grand snow
swift crag
#

Write Defaults just determines what value you get if the current motion doesn't set the property

swift crag
#

Show me in the hierarchy. Also show me which object in the hierarchy has the Animator on it.

arctic shore
#

and melee enemy has animator

#

and in enemy patrol is script that makes enemy patrolling

swift crag
#

okay, but what object are you trying to set the position of?

#

I'd guess MeleeEnemy.

arctic shore
#

yes

swift crag
#

If you can't move MeleeEnemy around at all with the animator turned on, that means that an animation is controlling the position of MeleeEnemy

#

You'd see it in the animation window like this

#

You may want to have animations that actually move the enemy's sprite around

swift crag
#

So the MeleeEnemy prefab would look more like this

#
  • MeleeEnemy <-- enemy component (if you have one)
    • Visual <-- animator
arctic shore
#

i only have default sprite in idle so it doesnt change and i dont see anywhere where my animation is controls enemy postion

swift crag
#

Again: ANY animation setting the position is all it takes

#

It does not matter if MeleeIdle doesn't set the position

#

It doesn't matter that you never leave the MeleeIdle state (which plays the MeleeIdle animation)

cold pier
#

Hi, I’m making a game on Unity 2D mode, and when I turn the "Control the selected camera in first person" at the "Cameras" a message appears in the consol "SceneView rotation is fixed to identity when in 2D mode. Thie will be an error in the furur versions of Unity". What can I do?

trail heart
lusty marten
#

How can you store calendars and dates in Unity? I need to keep track of what week of the year it is and having a hard time figuring out the best way to do it.

Basically I want to start with say January 7, 1980 and the be able to know the date for each subsequent week that follows.

tawny shell
#

Please is there a way to change those variables while running the game ?

#

I am new to Unity and noticed that when i print(t) which is the range(1, 100) field it does not change

wintry quarry
tawny shell
#

yeah but can i change it directly on unity

#

[Range(1, 100)] [SerializeField] private int t = 50;

wintry quarry
#

What makes you think it isn't changing?

tawny shell
#

even if i change the value it keeps printing 50

cold pier
wintry quarry
#

You'd have to show your code

tawny shell
#

ok

trail heart
sick jay
#

tooClose = Physics.SphereCast(transform.position, personalSpaceRadius, Vector3.zero, out spaceBubble, 0f, ~0, QueryTriggerInteraction.Ignore);

using a spherecast in this way causes the cast to be just a bubble of radius "personalSpaceRadius" on the transform.position, right? or am i misunderstanding how spherecasts work

wintry quarry
tawny shell
# wintry quarry You'd have to show your code
public class LayersHandler : MonoBehaviourPunCallbacks
{
    private Dictionary<string, GameObject[]> _allLayers = new();
    [CanBeNull] public GameObject childToEquip;
    [CanBeNull] public GameObject parentToUnequip;
    [Range(1, 100)] [SerializeField] private int t = 50;

    // Update is called once per frame
    void Update()
    {
        print(t);
    }
}
wintry quarry
wintry quarry
#

not a prefab or something

sick jay
#

When you make a spherecast does it not check a volume in a sphere shape from the point of origin?

wintry quarry
#

they are intended to be cast in a direction and a certain distance

#

That's what OverlapXXX methods are for

trail heart
sick jay
#

Oh so its more like a hyperspherical cast? Where it checks a sphere radius across a distance

cold pier
wintry quarry
#

(but the ball goes in a perfectly straight line)

tawny shell
sick jay
tawny shell
#

thanks @wintry quarry

wintry quarry
trail heart
wintry quarry
tawny shell
#

isn't there a way to do it on a prefab ?

wintry quarry
sick jay
cold pier
wintry quarry
cold pier
#

In my consol

wintry quarry
#

not that it's an ellipse

trail heart
cold pier
trail heart
trail heart
wintry quarry
sick jay
# wintry quarry What are you actually trying to achieve gameplay-wise?

When you run into walls or steep slopes, its very annoying because the player rigidbody will 'stick' to the wall instead of just sliding down it like normal. I'm writing into a script that will push the player in the normal to the walls face with the same amount of force that the player is attempting to put into the wall in the hopes that it will prevent that sticking. It seems like the best way since thats very similar to what happens in real life physics

#

The cast is just going to be around the player to check if its close enough to a wall

#

the personal space of the player

wintry quarry
#

then you can see if there's a wall there

sick jay
#

Yes, I was trying to figure out how the spherecast and capsulecast worked to better understand how to use them

wintry quarry
#

actually the reason we don't stick to walls in real life is simply because we have no way of applying force to ourselves midair

sick jay
#

Do you still think I should use an overlap?

wintry quarry
#

no I think you should use a spherecast or capsulecast in the direction the player is trying to move

#

depending on the player's shape

#

basically simulate where the player will be next physics frame with the cast

#

and see if it's hitting a wall

#

and prevent that motion so you don't push into a wall and create that sticking effect

sick jay
# wintry quarry actually the reason we don't stick to walls in real life is simply because we ha...

I would assume the sticky motion still happens even when the player is on the ground, but in real life you can push against a wall on the ground because your feet provide the force necessary. The force still happens even if you push against the wall in midair(ex moving very fast toward the wall) but generally as soon as you hit the wall the wall will push back with equal force enough to stop you instantly and depending on the material of the wall elastically put some force back into you to push you away from the wall

#

Thats what I think would be best to simulate in unity to prevent the sticking to the walls

wintry quarry
#

whereas in many games you have e.g. "air influence"

#

that's not a thing in real life

cold pier
sick jay
#

Yes, but I didn't say consistently, the force vector exists until you hit the wall, and then an opposing force vector from the wall pushes you back and since you cant move in midair, you dont continue pushing like in the game

wintry quarry
#

your willhave velocity towards the wall until you hit it and bounce

#

but you don't have a force pushing you

sick jay
#

The wall has to have a force pushing you

#

otherwise your acceleration wouldnt change and you would keep moving through the wall

wintry quarry
#

yes the wall will exert a force, that's why you stop moving

wintry quarry
#

you are one degree off in all this terminology

trail heart
#

Usually we want video game characters to be able to control their velocity in the air
Since the force to keep that velocity* comes from "nowhere" that's why it causes wall sticking
You don't go through the wall but velocity against the wall's friction prevents sliding down

wintry quarry
#

acceleration means "change in velocity"

sick jay
#

No, your acceleration too. You have an acceleration of 0 while moving fast toward the wall, but when you hit the wall, your acceleration goes negative until your velocity toward the wall is 0 or away from the wall

wintry quarry
#

sure

#

anyway, my suggestion is what I said above

#

you can take that or leave it

sick jay
#

Or maybe the player object has a friction on it too thats affecting it, let me test

trail heart
#

If so, 0 friction walls are usually a band aid solution at best

sick jay
wintry quarry
#

that will give you a cast that moves exactly as far as your player will actually move in the next physics simulation update

sick jay
#

Good idea, that would help in cases where the player is moving really fast as well

trail heart
livid pilot
#

Does anyone know how to integrate a splatmap into a shader graph? The way I have it is I isolate each color using smoothstep and/or subtract, and then multiply that with the texture, and add all textures back together for the final product, but the result is terrible and extremely pixelated for the base color, and utterly broken for the normals. I know it's more straightforward with terrain tools, but I'm using my own procedural terrain implementation.

sick jay
wintry quarry
sick jay
#

It's nice to know I was already looking in the right direction even if im on the wrong street

trail heart
sick jay
trail heart
#

I might let the character push against nonkinematic colliders when walking on solid ground, but if in air I'd instead not apply the force at all if there's an obstacle detected in the intended move direction

#

To prevent it from seeming like the character is getting momentum from the invisible rocket boots

#

But maybe that's not what you want, and maybe you can get by fine with a kinematic character controller
You can make them push objects just as well

#

It's a pretty common path to start making a transform based character controller, realise how terrible the collisions seem with a naive implementation
Then try to make it a nonkinematic rigidbody as a bandaid solution to that

sick jay
#

I think the type of game I am making would be better with a rigidbody over a kinematic controller, because I want it to be very physics and movement based

#

If I set up these type of interactions it would make adding new functionality a lot easier when it comes into contact with the player

eager bear
#

How can i do that a 2d object moves when a rotating force is applied?

verbal dome
#

This question is too vague

eager bear
#

Im using a physics material and the object bounces when i hit it

#

But not with rotation movement

#

I don't know how to explain it

verbal dome
#

Have you frozen that object's rigidbody rotation?

sick jay
#

Like spokes on a tire?

eager bear
wintry quarry
verbal dome
#

Yeah this is default physics behaviour

verbal dome
#

How are you moving the object that hits it?

eager bear
#

With a physics material

#

Im trying to do like a pong

trail heart
verbal dome
eager bear
#

I'm not using anything the object just moves when i hit it

verbal dome
#

I mean the object that is hitting it. How are you moving it

#

Things don't move by themselves

#

Except for rigidbody gravity

eager bear
#

With move

wintry quarry
#

"move" is not a way of moving things

sick jay
#

You mean when another object hits it and moves it?

wintry quarry
eager bear
eager bear
#

I don't know what type of movement is that

wintry quarry
eternal falconBOT
wintry quarry
#

What you showed doesn't have any type of movement at all

#

share the full script

eager bear
#

That's the full script

wintry quarry
#

You could also just read the code and tell us

wintry quarry
eager bear
#

It's from chat gpt so i don't understand a lot

verbal dome
wintry quarry
#

You don't understand what "full script" is either, apparently

eager bear
#

I don't

verbal dome
#

Paste the whole script file into a paste site.

wintry quarry
eager bear
#

Here?

wintry quarry
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

eager bear
#

Yeah i should probably learn instead of just asking chat gpt

#

Thanks for your time random gentleman's

sick jay
#

How can I tell the capsulecast to ignore only one layer rather than only apply it to one layer?

wintry quarry
#

Or you can invert a mask with ~mask

sick jay
#

Thank you

#

So ~0 means ignore all masks

wintry quarry
#

~0 means all layers will be hit

#

0 means no layers will be hit

sick jay
#

Thank you

#

What is common practice when dealing with defining ground? You can add a layer to something like a building to set it as a 'wall' mask, but what about the top of the building? You'd have to add another object that sits on top of it to let people have the correct ground interactions if you use layer masks to define grounds.

cold pier
#

Nobody know how to clear the message 'SceneView rotation is fixed.....UnityEnfine.GUIUtility:ProcessEvent (int,intptr,bool&)" ?

I look in tuto but found nothing and i cant send pictures...

sick jay
#

I just think the easiest way to define whats ground and whats walls would be to just check the angle of the object you are interacting with

wintry quarry
#

yes that

#

Most games don't need to distinguish

sick jay
#

I guess that makes sense

#

I was about to ask why many beginner tutorials wouldn't just use that and instead do either tags or layers to define ground but I guess most games dont need more than tags and layers

wintry quarry
sick jay
#

This includes Unity's junior programmer class

wintry quarry
#

There are also many ways to do everything and there's not always a clear "best" way or it depends on the requirements of the given game

#

Unity's own tutorials are also not always perfect.

cold pier
#

Discord was my last chance. Have nice night everyone

trail heart
#

Layers are kind of a dead simple way to do it, and they're a unity feature which is relevant for tutorials that mainly try to teach how to use unity

sick jay
#

Understood

#

I know I'm close but I'm doing something wrong.

{
    // Prevent the player from pushing into walls
    tooClose = Physics.CapsuleCast(orientation.position + Vector3.down / 2f , orientation.position + Vector3.up / 2f, personalSpaceRadius, rb.velocity.normalized, out closeWall, rb.velocity.magnitude * Time.fixedDeltaTime, ~0, QueryTriggerInteraction.Ignore);
    
    if (tooClose && climbScript.checkIfWall(closeWall))
    {
        Debug.Log("Attempting to force player away from wall");
        rb.AddForce(Vector3.Scale(closeWall.normal, rb.velocity));
    }
}```
I know the cast is hitting properly cause of the debug log, but its not pushing me away even if i set the personalSpaceRadius high.
wintry quarry
verbal dome
#

personalSpaceRadius is a funny variable name :P

wintry quarry
#

note that it's not going to push you away with this code because when you're not moving the cast isn't going to move

#

and if you are moving, this force would need to be stronger than your normal movement force to overcome it

sick jay
#

Would this be achieved with a projectonplane vector? where it takes the current vector direction and just projects it sideways rather than into the wall?

verbal dome
#

(What behaviour do you want?)

sick jay
sick jay
verbal dome
#

I would probably stop adding forces on the Y axis when I'm not on the ground

#

Some projection should be done too, if you want to be able to slide along the wall

#

Not sure how well Vector3.Scale(closeWall.normal, rb.velocity) works here.

sick jay
#

I'm going to try rb.AddForce(GetSlopeMoveDirection(rb.velocity, closeWall.normal), ForceMode.Force); public Vector3 GetSlopeMoveDirection(Vector3 direction, Vector3 plane) { return Vector3.ProjectOnPlane(direction, plane).normalized; }

#

This is the code i used to get movement for slopes, I'm sure it will still work on walls

rich ice
sick jay
rich ice
#

yup, but it works

#

all this extra code above is a good fix too (or so i assume, i've only read half of it)

sick jay
#

I can feel the force being applied, but I don't think its the correct amount. I'll try and figure out how to make it more precise

verbal dome
#

If I understand what you mean

sick jay
#

I do, that's what I'm trying to figure out how to do now

verbal dome
sick jay
#

What do you think I should use?

verbal dome
#

Don't you have something like a "target movement vector"?

#

What are you using to add forces/set velocity in the first place?

sick jay
#

I have a target max move speed, and a move direction

#
{
    // calculate movement direction
    moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;

    // on slope
    if (OnSlope() && !exitingSlope)
    {
        rb.AddForce(GetSlopeMoveDirection(moveDirection, slopeHit.normal) * moveSpeed * 20f, ForceMode.Force);

        if (rb.velocity.y > 0)
        {
            rb.AddForce(-slopeHit.normal * 80f, ForceMode.Force);
        }
    }

    // on ground
    else if (grounded)
    {
        rb.AddForce(moveDirection.normalized * moveSpeed * 10f, ForceMode.Force);
    }

    // in air
    else if (!grounded)
    {
        rb.AddForce(moveDirection.normalized * moveSpeed * 10f * airMultiplier, ForceMode.Force);
    }

    // turn gravity off while on slope
    rb.useGravity = !OnSlope();
}

private void SpeedControl()
{
    // limiting speed on slope
    if (OnSlope() && !exitingSlope)
    {
        if (rb.velocity.magnitude > moveSpeed)
        {
            rb.velocity = rb.velocity.normalized * moveSpeed;
        }
    }

    // limiting speed on ground or in air
    else
    {
        Vector3 flatVel = new Vector3(rb.velocity.x, 0f, rb.velocity.z);

        // limit velocity if needed
        if (flatVel.magnitude > moveSpeed)
        {
            Vector3 limitedVel = flatVel.normalized * moveSpeed;
            rb.velocity = new Vector3(limitedVel.x, rb.velocity.y, limitedVel.z);
        }
    }
}```
wintry quarry
#

so adding forces won't do anything really

#

I would basically expect code like this:

if (there is NOT a wall in the way) {
  // move normally
}
else {
  // there's a wall in the way
  // remove the portion of the desired movement vector that coincides with the direction towards the wall with Vector projection and subtraction
}```
sick jay
#

because as soon as the player moves again itll just get reset back

#

I'm going to change this void to a bool

#
private void MovePlayer()
{
    // calculate move vector if theres a wall in the way
    if (PersonalSpace())
    {
        Debug.Log("Attempting to stop player from moving toward wall");
        moveDirection = new Vector3(GetSlopeMoveDirection(rb.velocity, closeWall.normal).x * verticalInput, rb.velocity.y, GetSlopeMoveDirection(rb.velocity, closeWall.normal).z * horizontalInput);

    }
    else
    {
        // calculate movement direction
        moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;
    }
    // on slope
    if (OnSlope() && !exitingSlope)
    {
        rb.AddForce(GetSlopeMoveDirection(moveDirection, slopeHit.normal) * moveSpeed * 20f, ForceMode.Force);

        if (rb.velocity.y > 0)
        {
            rb.AddForce(-slopeHit.normal * 80f, ForceMode.Force);
        }
    }

    // on ground
    else if (grounded)
    {
        rb.AddForce(moveDirection.normalized * moveSpeed * 10f, ForceMode.Force);
    }

    // in air
    else if (!grounded)
    {
        rb.AddForce(moveDirection.normalized * moveSpeed * 10f * airMultiplier, ForceMode.Force);
    }

    // turn gravity off while on slope
    rb.useGravity = !OnSlope();
    
    
}```

I know im close to figuring it out, but im stuck here because I know the values I put in for the new moveDirection vector are incorrect but im not sure what to change them to
verbal dome
#

Use paste sites or at least add formatting to your snippets

sick jay
#

Will do

#

Its kinda funny the wall acts like a magnet

#

Maybe changing rb.velocity in the plane projection to just the vertical and horizontal inputs would get the correct direction?

#

for something like ``` moveDirection = new Vector3(GetSlopeMoveDirection(orientation.forward * verticalInput, closeWall.normal).x, rb.velocity.y, GetSlopeMoveDirection(orientation.right * horizontalInput, closeWall.normal).z * horizontalInput);

sick jay
#

After some testing, I think it would be better to just do an overlap. I can't get it working

round cairn
#

Does anyone know how to make lerp or smoothdamp or similar functions framerate independent?

My code:

transform.localPosition = Vector3.SmoothDamp(transform.localPosition, targetPosition, ref currentVelocity, swaySpeed);

Every tutorial I've seen on weapon sway uses a function similar to this (usually multiplying swaySpeed * Time.deltaTime), and obviously it's not framerate dependent.

verbal dome
#

Without context, the code you showed looks correct. Except that you use a "speed" variable in palce of the smoothTime argument

#

"Speed" would suggest that a higher value if faster. However a higher smoothTime value makes it slower

round cairn
#

When I manually set the framerate low, the sway goes absolutely crazy 😔

#

so maybe it isn't a framerate dependency issue but I actually have no idea

verbal dome
round cairn
#

i also used the old input system but it doesnt seem to work

timber tide
#

start debugging the values and see if the vectors are changing drastically

#

I assume delta time is implied. I don't really use smooth damp much

round cairn
#

ok its difficult to tell but I think the input vector spikes on lower frame rates

#

yea I set the framerate to 6 fps and the Mouse X input goes up to like 80 while max on 165 fps is 11

verbal dome
#

It is expected that you get higher mouse delta values with higher framerates

teal viper
#

Sounds like you have some framerate dependent code/logic

round cairn
#

I always assumed mouse input was framerate independent buttt

#

like is this not framerate independent?

teal viper
verbal dome
#

Mouse delta = how much your mouse moved during the last frame.

#

So it is inherently "framerate dependent", you just have to use it correctly

round cairn
#

Yea my mouse logic are both inside Update()

teal viper
#

That's not it.

#

You seem to be clamping the value with const values. That's making your logic framerate dependent as it would behave differently on different framerates.

round cairn
#

Oh my mistake I was using different code earlier, Im using this code now. Got rid of the clamp

verbal dome
#

It might be easier to pinpoint the issue if you show a video of both low and high FPS

round cairn
#

Ok Ill get on it

teal viper
verbal dome
#

Also if your swayTime is .15 and your frame takes more than .15 seconds, no idea how smoothdamp behaves then (or should behave)

#

I'm not even quite sure if smoothdamp is reliable on low framerates

#

One fix I can think of is to do multiple steps of smoothdamp with a smaller deltatime, when the frame's deltatime is high

round cairn
#

I sort of used smoothdamp out of desperation since I dont know how to use lerp

verbal dome
#

Like if you have 0.1 second frame, you would do 4 smoothdamps with 0.025 deltatime, for example

verbal dome
#

That's for Mathf.Lerp but it should apply to Vector3.Lerp as well

round cairn
#

ok thanks

static cedar
#

Could unity serialise other float values like +/-Infinity and NaN?

queen adder
sharp sigil
#

back to the problem i had yesterday in which when i dashed it just teleported me forward. I did the same with a basic cube and it worked fine. I get the input in update and set a bool is dashing to true, in fixedupdate i check if its true , set it to false and then add force to my player using addForce with the forcemode impulse but it just teleports me forward instead of a smooth dash.

naive pawn
#

make sure your rigidbody is interpolated, perhaps

sharp sigil
#

i set it to interpolate and it still does the same

#

i mean i spawned a cube and did the same with it and it worked fine

#

nvm it was the animator ig

#

but still i think i dash but its just too fast is there a way how i can slow it down?

verbal dome
#

You can also add it over time, in a coroutine for example

sharp sigil
#

then i just dash a little distance

forest flume
#

Please enlighten me what you did brother 🙏

sharp sigil
forest flume
sharp sigil
#

but i gotta learn what they are and how to use them :)

verbal dome
sharp sigil
#

aight im learning how they work rn

verbal dome
#

This can ofc be done without a coroutine but they are good to learn

sharp sigil
#

i know what they do but i just dont know how to use them yk

verbal dome
#

You can find examples in the docs etc

sick jay
#

I have a Transform that I want to keep in its original spot, but I want to make another Transform variable based off the transform but shifted 1.0f in the y axis. How can I go about this?

#

A Transform is a location and rotation, correct?

#

And scale*^

#

I think I figured it out,

cameraPos.position = orientation.position + Vector3.up / 2f;```
#

(Decided to make it 0.5 and not 1)

low raven
#

Hey Chat

#

!cs

eternal falconBOT
quick pollen
#

why does the unity documentation create 2 object pools for a single type?

#

its just so difficult to understand what is going on

#

all I want is object pooling for projectiles

verbal dome
#

That doesn't create two pools. It's an if-else

quick pollen
#

the first 2 lines

#

theres 2 IObjectPool<ParticleSystem>s being defined

#

one of them is private other one is public

verbal dome
#

The second one, Pool is just a property that has a getter for the private field m_Pool

#

The idea here is that it doesn't create m_Pool until it is actually needed

quick pollen
#

what if you just make m_Pool public?

#

I want to create it during loading, not during gameplay

#
using UnityEngine;
using UnityEngine.Pool;

public class ObjectPoolingProjectiles : MonoBehaviour
{
    [SerializeField] GameObject bullet;
    public IObjectPool<GameObject> m_Pool;
    public static ObjectPoolingProjectiles Instance;
    private void Awake() {
        m_Pool = new ObjectPool<GameObject>(CreatePooledItem,
        OnTakeFromPool, OnReturnedToPool,
        OnDestroyPoolObject, true, 20, 30);
        Instance = this;
    }
    GameObject CreatePooledItem()
    {
        GameObject go = Instantiate(bullet);
        go.GetComponent<BasicBullet>().pool = m_Pool;
        return go;
    }

    void OnReturnedToPool(GameObject projectile)
    {
        projectile.gameObject.SetActive(false);
    }

    void OnTakeFromPool(GameObject projectile)
    {
        projectile.gameObject.SetActive(true);
    }

    void OnDestroyPoolObject(GameObject projectile)
    {
        Destroy(projectile.gameObject);
    }
}```
#

this is what I have currently

verbal dome
quick pollen
#

its not a big snippet so I won't put it on hatebin

#

right now, the problem is that all this does is instantiate projectiles whenever I fire

#

it doesnt instantiate them all at once and then activate/deactivate them

verbal dome
#

Does it not instantiate 20 objects when you initialize it? That's what you are passing into the defaultCapacity argument in the constructor

quick pollen
#

nope

#

I call GameObject proj = ObjectPoolingProjectiles.Instance.m_Pool.Get(); to fire

verbal dome
#

Ok apparently it just sets the capacity of the list

quick pollen
#

am I meant to create a loop?

verbal dome
quick pollen
#

so if I call Release and then try to use Get again, it works properly

#

but the first projectiles that you fire get instantiated when you fire

#
    GameObject[] gos;
    private void Awake() {
        m_Pool = new ObjectPool<GameObject>(CreatePooledItem,
        OnTakeFromPool, OnReturnedToPool,
        OnDestroyPoolObject, true, 20, 30);
        Instance = this;
        for(int i = 0; i < 20; i++){
            gos[i] = m_Pool.Get();
        }
    }
    private void Start(){
        foreach(GameObject go in gos){
            m_Pool.Release(go);
        }
    }```
quick pollen
#

i dont even get why I have to do this manually

#

i dont think this worked like this before

#

it feels like it completely ignores the whole capacity thing

verbal dome
#

As in, List<T>.Capacity or similiar

quick pollen
#

but it didnt work like this before?

#

then what does maxSize set?

languid spire
quick pollen
#

not sure how to fix it tho

#

doing new() doesnt do anything

languid spire
#

new GameObject[20];
basic C# knowledge

quick pollen
#

it does it, alright

#

but I still get this error

#
    void OnReturnedToPool(GameObject projectile)
    {
        projectile.gameObject.SetActive(false);
    }```
#

says that projectile is null

languid spire
#

yes you have created a pool but there is nothing instantiated in it. So it is full of nulls

verbal dome
verbal dome
verbal dome
#

How does it work then? 🤔

languid spire
#

the createpooleditem callback needs to do the instantiation

quick pollen
#
    private void Awake() {
        gos = new GameObject[100];
        m_Pool = new ObjectPool<GameObject>(CreatePooledItem,
        OnTakeFromPool, OnReturnedToPool,
        OnDestroyPoolObject, true, 20, 50);
        Instance = this;
        for(int i = 0; i < 20; i++)
            gos[i] = m_Pool.Get();
    }
    private void Start() {
        foreach(GameObject go in gos){
            m_Pool.Release(go);
        }
    }```
languid spire
#

show your CreatePoolItem code

quick pollen
#

wdym

#
    GameObject CreatePooledItem()
    {
        GameObject newPooledObject = Instantiate(bullet);
        newPooledObject.GetComponent<BasicBullet>().pool = m_Pool;
        return newPooledObject;
    }```
languid spire
#

and have you debugged any of this?

verbal dome
quick pollen
#

the nullreference happens once when the game boots, thats it

languid spire
languid spire
verbal dome
#

Alfy already showed that CreatePooledItem instantiates it

quick pollen
#

but appareantly CreatePooledItem only gets called when there's no items in the pool and you call Pool.Get()

languid spire
#

Ah, I hadn't scrolled that far back

quick pollen
#

which shouldnt be the way it works

#

it should instantiate 20 objects on scene load

verbal dome
#

Where does it say that it should

quick pollen
#

and instantiate more if I'm trying to Get from the pool when theres no free objects

quick pollen
#

I used this before

verbal dome
#

(I mean, to me, intuitively it would make sense if it automatically instantiated the min amount)

quick pollen
#

but now it just doesnt

quick pollen
#

maybe I remember wrong, but thats how I remember it working

#

ill just try

            if(go != null)
                m_Pool.Release(go);```
#

although I have an idea

#

I feel like it happens because I click on the play button

#

and clicking is how you fire

#

so maybe you try to fire before the items are loaded in?

#

no that cant be it...?

verbal dome
#

You can use Ctrl + P to enter playmode too

#

You can also check if m_Pool is null and debug.log it

quick pollen
quick pollen
#

kinda cheaty but yeah

languid spire
#

that did not 'fix' anything, it just hides the error in your logic

quick pollen
#

well, it no longer tries to release nothing

verbal dome
#

Are you still initializing it in Awake, and calling Release in Start?

quick pollen
#

i mean, it tries, but it cant

verbal dome
quick pollen
#

yes

#

lemme get a hatebin

languid spire
#

which should not be happening in the first place. you are addressing symptoms instead of the actual problem

quick pollen
verbal dome
#

        for(int i = 0; i < 20; i++)
            gos[i] = m_Pool.Get();```
#

vs

#
        gos = new GameObject[100];```
#

Do you see the mistake?

languid spire
quick pollen
languid spire
#

you are creating an array of 100 objects but only filling the first 20 of that with something, the other 80 will be null

quick pollen
#

yeah, setting it to 20 works

quick pollen
languid spire
#

no, null ref will abort the code

#

you seriously need to learn some c# basics

quick pollen
languid spire
#

probably called in Update

quick pollen
#

my bad

#

I mean, I coded, but in c++, which is completely different

languid spire
#

yeah, C++ will not help much with basic C#

tough plinth
#

Hey everyone!
Just got a quick question related to script-writing.

So there is a task that asks to to code an object to move in a specific direction.

But in Unity course there were 2 different types of writing Movement script:

Which one is better to use?

#

Why are they up to using 2nd option over 1st, if these scripts almost the same and do the same job?

languid spire
#

they do exactly the same thing

#

and, both are wrong

verbal dome
#

From the source code. Translate(x, y, z) just calls Translate(vector)

tough plinth
verbal dome
#

The first Translate in your code includes a float multiplication, the second one does a vector multiplication so there's a micro difference

languid spire
tough plinth
#
  1. works with numbers
  2. works with Vector's object?
verbal dome
tough plinth
#

Yeah

verbal dome
#

I gotta say though, that particular Unity learn lesson is bad, it teaches you to move a rigidbody with transform, which is incorrect

#

It will lead to oddities in the physics, like missed collisions and glitching

tough plinth
#

So, I assume it's a good course to get into unity, but you need to re-learn some of the aspects that they taught?

signal pollen
#

Hello! I would like a little help. I am trying to make a simple mini-game where you place little blocks on an isometric map to prevent floods. I am following the "Junior Programming Pathway" course and am doing the "lab project as recommended. I am having a little struggle trying to make a grid system

#

(Concept art that I make quickly in pixel art, but I want to build it in 3D)

west radish
signal pollen
#

I want to be able to make a 3D-storage where the positions, data and other information of blocks are stored, can be edited in the Unity Editor mode and in game as well. And then Exported later if possible as a spreadsheet

tough plinth
#

In course I heard that it's called a "hard-coded number"? And making variables makes it easier to change values

verbal dome
#

A C# array

signal pollen
#

Is there a good tutorial I ccan follow to do so?

#

I scraped together a bunch of information from other (non tutorial, and actually "minecraft clone" tyoe) YT vid and made some progress but I think I need to scrap it.

#

I made this using Unity's in built system, but the collision system isn't what I want, unfortunately. I don't understand it and I dont know how to read for neighbouring blocks

verbal dome
#

It could be a 3 dimensional array of your custom type. Each item in the array would store info about the cell that it refers to

tough plinth
#

And also a small question:

You can define variables only in functions such as Start() and Update ()?

You can't define them before Start()?

verbal dome
#

How much experience do you have in coding/unity though?

#

This is not the simplest beginner project tbh

signal pollen
#

I have basic experience with coding, and I started Unity on Wednesday

verbal dome
#

Unless the other field is static/const i guess

signal pollen
#

In a bigger context question, I am learning Unity for a Uni project where I need the 3D-positional data to be exported (Hopefully in real time)

#

But one step at a time

tough plinth
signal pollen
#

Mini-projects to learn, y'know?

signal pollen
#

Also, I know I should probably start from scratch

#

Should I try making a different mini-game first?

verbal dome
#

Probably

signal pollen
#

Damn

verbal dome
#

If you can't begin to think how to implement the 3D array, it's likely too early for that

signal pollen
#

I don't know really how to start

quick pollen
#

btw, if I do this, do I need to do new()?
public List<IObjectPool<GameObject>> m_Pool;

verbal dome
#

For a beginner

signal pollen
#

Maybe I should start with a car that moves from one place to another

languid spire
signal pollen
quick pollen
languid spire
#

exactly like

quick pollen
#

I basically want to make it so I can have different object pools for different projectiles

verbal dome
signal pollen
#

But I think I will put this complex project on hold and try a "move a car from one town to another over pre-built iso metric plane"

quick pollen
#

so if I want to add a new projectile type, I just add a new prefab to pool

signal pollen
verbal dome
signal pollen
#

But for now I think, on your recommendation, I will put this project on hold and make a simpler one.

#

Just drive from point A to B over Terrain, using the 3D collision blocks given in Unity

#

Just to continue down the Junior Programming course

quick pollen
west radish
quick pollen
#

what if I want to do

        for(int i = 0; i < bullets.Count; i++){
            m_Pool[i] = new ObjectPool<GameObject>(CreatePooledItem,
            OnTakeFromPool, OnReturnedToPool,
            OnDestroyPoolObject, true, 20, 50);
        }```?
signal pollen
#

Yeah, conceptually, I understand that. I just dont know how to code it/ implement it

quick pollen
#

so every pool has its own projectile

#

how can I differentiate?

verbal dome
#

Create a separate pool for each and have them use a different prefab

quick pollen
#

thats what I'm trying, but I dont want to create new scripts for every single new projectile

#

like how can I tell them which prefab to use?

verbal dome
#

You'd obviously use the same script

#

Add a new component of this script's type for each bullet type

#

Or you can put it all into one script, up to you

quick pollen
#

I have no way of telling the function which projectile to use

quick pollen
#

thats my issue

verbal dome
#

Then put the pool into its own class, non monobehaviour

quick pollen
#

I basically want a list of pools, and to be able to access any of the pools by just using a number

verbal dome
#

And have the one monobehaviour hold a list of those classes

signal pollen
#

Anyway, thank you for the recommendations and advice. I feel like if I wasn't told that it is above my skill-level I would have kept banging my head against this wall.

languid spire
verbal dome
#

That would work too

ivory bobcat
quick pollen
verbal dome
#

Instantiate is static

#

You can call it from anywhere

#

UnityEngine.Object.Instantiate or GameObject.Instantiate etc.

quick pollen
#

oh really

#

alright

languid spire
quick pollen
#

and then I just create a list of classes?

verbal dome
#

In a monobehaviour you can just do Instantiate because this is already a UnityEngine.Object so it has Instantiate as a member

west radish
languid spire
quick pollen
#

this makes like no sense

#

System.Linq.Expressions.Expression<Func<int, int>> e = x => x * x;

verbal dome
ivory bobcat
quick pollen
signal pollen
#

Thank you, I will note that. But I want to just get a smaller/simpler game from what I learnt in the course first before I continue to entrench myself in the same concept continually

languid spire
quick pollen
#

or being able to see how it works

#

but it literally shows one extremely rudimentary example, and then an extremely complicated one

#

the rudimentary one isnt enough to understand anything, and the complicated one is too much to be able to take anything out of

languid spire
#

have you ever used Coroutines in Unity?

quick pollen
#

I have

languid spire
#

have you used a yield Wait statement ?

quick pollen
#

even those ones were explained quite weirdly until I implemented it myself and it just worked

quick pollen
languid spire
west radish
languid spire
#
yield return new WaitUntil(() => isDone);
quick pollen
#

from what I could gather I need an Action<> lambda expression

#

or statement lambda

languid spire
#

correct

west radish
#

I'd also add using System.Linq.Expressions; to the top of the file, it will shorten how long the line needs to be

languid spire
#

do not need Linq for this

west radish
#

true

quick pollen
#

i was about to say, it works without

echo sand
#

any idea how i can fix this? idk understand what it means, my item is a scriptableObject

west radish
#

though it is in the original line so its interesting how it got there

languid spire
west radish
#

Honestly im not sure why the Expressions part is in the original line either

echo sand
#

called by this

languid spire
west radish
#

public T[] InitializeMap<T>(Func<int, int, T> factory) any time I've used Func before and it only ever needs using System;

quick pollen
#

so I have this

#

actually these

#

so inside the Instantiate, I want to be able to set what projectile to use

echo sand
quick pollen
#

would I need to call create inside of CreatePooledItem?

languid spire
# quick pollen so I have this

wrong place, you need the lambda here

new ObjectPool<GameObject>(CreatePooledItem,
            OnTakeFromPool, OnReturnedToPool,
            OnDestroyPoolObject, true, 20, 50);

in place of the CreatePooledItem

verbal dome
#

You need a Func<GameObject>, not action

#

Func allows a return type, Action only takes inputs

quick pollen
#

oh, I see

languid spire
#

he does not need a Func at all

quick pollen
#

something like this?

languid spire
#

all he needs is a lambda to capture i and pass it to a method

quick pollen
#

wait I'm confused now

languid spire
verbal dome
#

Yeah nevermind the Func part

quick pollen
#

I cant pass it to the CreatePooledItem method

verbal dome
#

You can if you use a lambda and add an int parameter to CreatePooledItem

quick pollen
#

I can't add any parameters to CreatePooledItem

verbal dome
#

Why do you say that?

quick pollen
languid spire
#

look, your CreatePooledItem will not take a parameter as you currently have it
So, you modify CreatePooledItem to take an int parameter
But, this makes the signature required by Objectpool invalid
So you use a lambda to correct the signature

quick pollen
#

it requires a System.Func

#

not an action

verbal dome
#

You are missing the lambda part

verbal dome
quick pollen
#

wouldnt I need a Func then, not an Action?

verbal dome
#

I just said that createpooleditem is your Func

#

You need to use a lambda expression to call it with the i as an argument

quick pollen
#

hold on

quick pollen
#

would I need CreatePooledItem to call the Lambda?

#

im sorry im being really slow right now

verbal dome
#

You don't need the action

quick pollen
#

then....?

languid spire
#

look, this is so simple

        m_Pool[i] = new ObjectPool<GameObject>(() =>
        {
            int x = i;
            return CreatePooledItem(x);
        },
        OnTakeFromPool, OnReturnedToPool,
        OnDestroyPoolObject, true, 20, 50);
...
    GameObject CreatePooledItem(int i)
    {
        GameObject newPooledObject = Instantiate(bullets[i]);
        return newPooledObject;
    }
quick pollen
#

what is the ...?

slate haven
#

I am making a grid system, the catch is, i dont have a pre-defined width and height with me. I have a plane, and i want all the tiles to be fit upon it (consider chessboard). I have total amount of tiles I want to fit upon a plane of some size. I tried using renderer.bounds.size but it gives huge amount of value which i cannot use as height/width. Please help me out here!

languid spire
#

commment to illustrate other code

verbal dome
#

(Deleted my reply since it had the variable capture problem)

slate haven
naive pawn
#

"made in 3d" doesn't make everything else 3d

#

planes in 3d are by definition 2d

slate haven
naive pawn
#

seems pretty 2d to me

slate haven
#

yeah

#

but still same question

verbal dome
naive pawn
#

you have a total width/height, and a tile count?

verbal dome
#

It's a 3D concept too

naive pawn
#

just divide them

slate haven
quick pollen
#

yeah I think I get it

naive pawn
slate haven
#

How do I calculate the width and height

#

I want 120 blocks to be spawned upon that plane, equally aligned

verbal dome
naive pawn