#💻┃code-beginner

1 messages · Page 434 of 1

topaz mortar
#

my game is Steam only

zenith cypress
#

the only thing I can think of is if the model doesn't have lightmap uvs so it does a goofy (it's a toggle on the mesh if you want to generate them, otherwise you have to bake your own into UV2/UV3)

hazy crypt
#

Hi guys, I have a question about inputs. Im making a racing game where the player can quick restart the level pressing the R key. When I do this, I want the game to detect that Im still holing the accelerate key (W, in this case). Ive had a poke about online and cant see how to achieve this, would anyone know how?

#

At the moment, I hold accel, i go forward. I reset, not letting go of accel, and unity doesnt detect an input on relaoding the scene

#

i hope this makes some sense

rich adder
#

consider manually resetting the scene objects instead of reloading an actual scene

atomic yew
#

I deleted some projects to free up memory but it didn't work. All projects have this problem. Did I accidentally change a setting without knowing it? Does anyone out there know how to drop 60FPS startup to 2 fps out of nowhere? Everything has peaked. Suddenly everything went up.

hazy crypt
#

It is a very long way around though

#

If its the only way then ill have to do it I guess

rich adder
#

there is extra work but its worth it imo

#

if you're used to doing things like object pooling its not that much different resetting states

hazy crypt
#

Im a very beginner so stuff like this is new and confusing

#

But im willing to give it a go

rich adder
#

give it a shot, take note of what exactly changes in your scene and put it back how it was

hazy crypt
#

I guess Ill set up a restart event in my event manager and then ask everything its original state, then go back to that on the event stary

rich adder
#

yeah a static event could work too

hazy crypt
#

what would that entail?

rich adder
#

if you want to make easier as beginner you could replace it for a UnityEvent and do everything in the inspector

#

as long its on a manager type script as you said, should be present in the scene

hazy crypt
#

Im not sure I completely understand, but sure I think ill give that a go

#

I am surprised that the input manger system doesnt have this capability by default tbh

rich adder
hazy crypt
#

But I suppose it has limits

rich adder
#

then just make a Resetting() type of method on whatever you want

#

and plug in the inspector

hazy crypt
#

Ill read the documentation to understand what you did

#

Thank you very much for your help

rich adder
#

its just exposing the field in the inspector

#

same as public only its for private

hazy crypt
#

Okay I see

fervent abyss
#

Im trying to get my layers numbers using theLayer.value but it returns these numbers.....

strong wren
short hazel
fervent abyss
#

how can i convert layer mask to its order number?

short hazel
#

Yep so it's normal to see it like that. Layer masks are bit fields, where each bit of the value represents a layer.
It printing 512 would mean the 9th layer is active (2⁹ = 512)

silver lagoon
#

When declaring data types, the format is usually:
public/private dataType identifier
Is there a data type that allows me to call a script? I'd like to do it so I can assign the script in the editor, similar with:
public GameObject exampleObject
Is there anyway I can do this, or do I have to specifiy the name of the script I want to call as the data type?

short hazel
#

You will be able to drag-drop the script, or an object that has it attached in the Inspector

winter tinsel
#

uh code makes camera turn not player move :/

#

why does it rotate the camera?

rocky canyon
#

no clue, theres no rotation code there.. and no camera reference

short hazel
short hazel
#

Increase the force, in the Inspector. The value you set in code is overwritten by the one you set in the Inspector

#

It might be at 1 in there

winter tinsel
#

okay it works now for some reason

#

but the force is too much the rigidbody just teleports lol

short hazel
#

Decrease it

#

Until it feels good

grave furnace
#

No idea how to instantiate a prefab

short hazel
winter tinsel
#

the camera is a child rn

#

if that changes anything

short hazel
#

The object is falling on its side. Constrain the rigidbody so it cannot rotate around X or Z

winter tinsel
#

how

#

wait

short hazel
#

It's an option you can activate on the Inspector of the rigidbody

winter tinsel
#

ah

winter tinsel
#

yk like an fps

#

if its more complex than just a few sentences then ill go reasearch it

slender nymph
#

obligatory: use cinemachine

winter tinsel
#

what is cinemachine

short hazel
winter tinsel
#

i have not

#

okay ill go look at it

molten dock
#

are there any coding things that i should avoid when starting my first big game

slender nymph
#

the biggest thing to avoid is not understanding the fundamentals. if you understand what you are doing then you'll know what does and does not work

short hazel
#

Changing variables values in ScriptableObjects thinking they'll be saved for the next play session is a common one

winter tinsel
#

i know better now lol

rocky canyon
#

all good.. means ur not using them in the first place most likely

short hazel
#

You haven't touched that feature yet, you'll be using them in the future

winter tinsel
rocky canyon
winter tinsel
summer stump
# winter tinsel why?

Because it is very slow and there is never a reason to use it
It searches every object in the scene for something matching a NAME, which is very brittle too

slender nymph
# winter tinsel why?

the Find methods are slow because they typically have to search the entire hierarchy. there are almost always better ways to get a reference to another object

rocky canyon
winter tinsel
rocky canyon
#

its probably in the top left corner as a dropdown

winter tinsel
#

found it

grave furnace
short hazel
grave furnace
#

im so confused rn lol

rocky canyon
#

GameObject prefab;
Instantiate(prefab, position, rotation);

slender nymph
short hazel
grave furnace
molten dock
#

i used alot of static variables in my last game which made stuff alot easier but is bad i heard

summer stump
short hazel
#

Unless that was added too

slender nymph
#

maybe someday 🙏

molten dock
#

what is the good alternative to static variables

#

forgot sorry

summer stump
#

Generally just NOT static variables though

molten dock
#

i use them to acsess values between scripts

slender nymph
molten dock
#

why is there some guy at the bottom

summer stump
#

Note that Hariedo (who made this) doesn't even include statics as an option haba

molten dock
#

i will avoid statics

#

tyty

summer stump
molten dock
#

i see

slender nymph
# molten dock i will avoid statics

you don't need to actively avoid static. you just need to make sure you are using it when appropriate. for example, using it to access a variable on another object is not the appropriate way to use it. Using it for a variable that is not used for any specific instance of an object and has no need to be an instance variable would be an appropriate time to use a static variable. or implementing the singleton pattern (though this pattern is also often abused by people not understanding how to get a proper reference)

trail harbor
#

Am I right about using Cloud Save client sided could cause problems such as the client using cheat engine to modify values? I don't know how cheat engine works properly, but I keep looking for ways to make the save & load server sided but it's too complex for me at the moment, am I safe to go with clientsided?

strong wren
trail harbor
#

I guess I'll just use clientside till I know how to do server side then

zenith cypress
summer stump
#

I'm sure he would share them if you asked though!

uncut shoal
#

I am procedurally generating a mesh at runtime. How do I draw that mesh without creating a meshrenderer?

wintry quarry
#

Or use Graphics.RenderMeshXxx

scenic saffron
#

how do i round a float in unity without using Mathf.Round? im also converting to a string if that helps

slender nymph
uncut shoal
wintry quarry
#

What says that

#

You'd have to show the code

uncut shoal
#

Graphics.RenderMesh() this for the 'Graphics.RenderMesh' doesn't exist

#

and RenderParams rp; for 'RenderParams doesn't exist'

wintry quarry
uncut shoal
#

o right]

#

Yep it works, thanks!

silver lagoon
#

I'm using the following code to make an object chase/home in on another object. When the chasing object gets close, there is a noticable increase in speed. Additionally, if the target object has no collision, the chaser will pass over the target (as is expected), but will also maintain its course and begin moving away from the target object. How do I stop both these issues from occurring?

playerPos = new Vector3(target.transform.position.x, target.transform.position.y, target.transform.position.z);
direction = playerPos / (playerPos.magnitude);
direction.Normalize();
rb.velocity = Vector2.zero;
rb.AddForce(direction * moveSpeed);

modest dust
#

This doesn't make any sense

#

First of all, why not just
playerPos = target.transform.position;

#

Second of all, your direction calculation makes absolutely no sence

#

You're dividing a position by it's magnitude

summer stump
modest dust
#

Instead of doing
directon = (targetPos - myPos).normalized;

#

Look up vector math

#

And well, think logically too - a direction spans from point A to point B and your calculations only included variables coming from point B. Read your code carefully next time and analyze it + learn how to debug values to know what's going on

cinder crag
#

does anyone know why , im not movind when im using the new input system? i added the Move method as an event to well Move InputAction

summer stump
#

moveDirection = ctx.Read

cinder crag
#

But it still doesn't really work

#

i forgot to put the GetReferences() method in start

#

smh

slender nymph
#

why not just make the change that was suggested?

#

and if it is still not working then, then you probably haven't enabled the input action(s)

summer stump
misty pecan
#

which collider2d should i use for a path in a tower defence game

cinder crag
summer stump
#

Also, stop doing screenshots

night raptor
summer stump
#

Share the whole code

#

Lastly, did you enable the input actions as boxfriend said?

misty pecan
summer stump
#

!screenshots

eternal falconBOT
#

mad No

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

modest dust
#

Box collider most likely

summer stump
misty pecan
night raptor
rich egret
#

hi, someone know what to do if string reference it doesn't appear? (There is a key)

cinder crag
misty pecan
night raptor
modest dust
misty pecan
#

I got it working by editing the polygon collider thanks

cinder crag
#

alright fixed it , it works now with how aethenosity suggested just ahd to change the default map to Player and the default Scheme to KeyBoard & Mouse

primal trench
#

how do i make it so a raycast only detects collisions of a certain layer?

#

(in code)

slender nymph
#

pass a layermask into the raycast method

polar acorn
primal trench
#

ah ok, thanks!

sand heath
#

i always forget which away around it is

summer stump
sand heath
#

Window > Analysis > Input Debugger

summer stump
cinder crag
summer stump
cinder crag
heady pawn
#

can someone say me why my player jump so hight plz

#

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

public class playermov : MonoBehaviour
{
[SerializeField] private float speed;
private Rigidbody2D body;

private void Awake()
{
    body = GetComponent<Rigidbody2D>();
}

private void Update()
{
    body.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, body.velocity.y);

    if (Input.GetKey(KeyCode.W))
    body.velocity = new Vector2(body.velocity.x, speed);
}

}

#

this is my code can you explain me how to make im jump less low

wintry quarry
eternal falconBOT
heady pawn
#

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

public class playermov : MonoBehaviour
{
[SerializeField] private float speed;
private Rigidbody2D body;

private void Awake()
{
    body = GetComponent<Rigidbody2D>();
}

private void Update()
{
    body.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, body.velocity.y);

    if (Input.GetKey(KeyCode.W))
    body.velocity = new Vector2(body.velocity.x, speed);
}

}

#

i dont uderstand sorry

wintry quarry
#

for how to post your code correctly

#

stop spamming your unformatted code

heady pawn
#

im french i dont uderstand

#

the bot

#

i uderstand you

wintry quarry
#

Use Google Translate

heady pawn
#

🥲

heady pawn
#

'''cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class playermov : MonoBehaviour
{
[SerializeField] private float speed;
private Rigidbody2D body;

private void Awake()
{
    body = GetComponent<Rigidbody2D>();
}

private void Update()
{
    body.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, body.velocity.y);

    if (Input.GetKey(KeyCode.W))
    body.velocity = new Vector2(body.velocity.x, speed);
}

}
'''

#

🤷‍♂️

summer stump
#

It is backticks, not single quotes

#

` not '

heady pawn
#

ok my bad

summer stump
#

You can always just copy paste it from the bot

#

also, you are using the same variable for jump as you are for movement speed. That is likely not what you want

heady pawn
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class playermov : MonoBehaviour
{
    [SerializeField] private float speed;
    private Rigidbody2D body;

    private void Awake()
    {
        body = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        body.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, body.velocity.y);

        if (Input.GetKey(KeyCode.W))
        body.velocity = new Vector2(body.velocity.x, speed);
    }
}
#

sorry 🥲 for the time i take you

summer stump
#

which..... seems like a poor thing to do

heady pawn
#

so wath should i change?

summer stump
#

Simple as that

#

turn body.velocity = new Vector2(body.velocity.x, speed); into body.velocity = new Vector2(body.velocity.x, jumpSpeed); and also create jumpSpeed
Change the variable to how you want the jump to feel

heady pawn
#

ok thanks i uderstand i'm gonna try right now

raw token
#

Worth a mention that Input.GetKey() will return true for every frame that the key is pressed - there are alternatives which will only return true for the frame in which the key is first pressed/when it's released

summer stump
#

Oh yeah, ABSOLUTELY this ^
Unless you wanna fly, use a single frame input instead of held input

heady pawn
#

like this?

#

thanks i solve the problem and sorry to take your time i'm new in unity and english is not my first language so...

fading mountain
#

Guys, I have no idea why I'm getting these syntax errors from this code. I know I probably look like an idiot and this is something really simple but I just can't see what wrong with it XD
for (int i = 0; i < playerLives; i++;) { Instantiate(heart, heartContainer, false); }
Errors: (26,45): error CS1026: ) expected
(26,46): error CS1513: } expected

eternal needle
#

but also that Instantiate looks wrong with the parameters

fading mountain
fading mountain
dusky sentinel
#

Hi! I need to make a dialogue system that loads the monologue one by one instead of having them load all at the same time. How can I make this happen?

heady pawn
#

ooooohhhh i want to know that too

slender nymph
heady pawn
#

thanks

half egret
#

As a starting point, at the very least it'll give you a frame of reference

opaque ibex
#

hellooow

#

I made a turret on Blender. It has 3 bones - 1 for tower, 1 for turret head and 1 for the turret. I followed a tutorial on how to properly export the model as FBX and import on Unity. I added a sphere mesh on unity and put a script on it. The turret(the whole thing from blender) supposed to move whenever it get near the sphere but it the doesn't. On the turret, I added meshcollider with convex checked, Rigidbody, and a navmesh. Somehow, whenever I remove the bones, the addforce thing works on the turret but I added the bones for a reason and don't want to remove it. I hope someone could help me or guide me with this problem. Thanks.

mint remnant
#

Adding bones to it sounds like it would over complicate things, so just out of curiosity, what was the reason to add them?

eternal needle
#

A lot of this also doesnt make sense like
"added a sphere mesh on unity and put a script on it"

opaque ibex
opaque ibex
opaque ibex
#

and this is the script

#
using UnityEngine;
using System.Collections.Generic;

public class PlanarGravityScript : MonoBehaviour
{
    public Transform atmosphere;
    public float gravitationalRadius = 10f; 
    public float gravitationalForce = 10f;   
    public Color gizmosColor = Color.red;

    void Start()
    {
        Physics.gravity = Vector3.zero;
    }
    void Update()
    {
        Collider[] colliders = Physics.OverlapSphere(transform.position, gravitationalRadius);

        foreach (Collider collider in colliders)
        {

            Rigidbody rb = collider.GetComponent<Rigidbody>();

            if (rb != null && rb != GetComponent<Rigidbody>())
            {
                Vector3 direction = transform.position - collider.transform.position;
                float distance = direction.magnitude;
                float gravityStrength = gravitationalForce / distance;
                rb.AddForce(direction.normalized * gravityStrength * rb.mass);
            }
        }
    }
    
    void OnDrawGizmos() {
        Gizmos.color = gizmosColor;
        Gizmos.DrawWireSphere (transform.position, gravitationalRadius);
    }
}
#

and instead of the tower... I'll use this another object which has bones too but only 2 bones.

molten dock
#

i am trying to find whats causing this error but im not sure, its the "object not set to an instance of an object" error and its this line foreach (IDataPersistence dataPersistenceObj in dataPersistenceObjects)

#

i think the IDatapersistence script shouldnt need to be attatched to a gameobject since its an interface not a monobehavior

polar acorn
molten dock
#

could you explain please

#

like it does not exist#

polar acorn
molten dock
#

okay

#

how do i make it exist lol

mint remnant
#

new one up

#

might help if you post some of the code leading up to that line

molten dock
#

i think its too much for discord ty for putting me in the right direction

eternal falconBOT
polar acorn
mint remnant
#

the quick check is right before that line add a debug line that prints out if it is null, then at least you know to look for that specifically

eternal needle
opaque ibex
polar acorn
summer stump
opaque ibex
#

I know. the debug won't show up

polar acorn
opaque ibex
#

it is running.

summer stump
polar acorn
opaque ibex
#

It affect other things but not the mesh with bones

summer stump
#

If the log isn't showing up, the code is not running

#

You either put the log in the wrong spot, or hid logs in the console

teal viper
#

Assuming the log messages are not hidden

opaque ibex
summer stump
#

Maybe.... show what you did?

opaque ibex
#

okay.. I'll record a screen

summer stump
#

Just send the code. No recording needed

opaque ibex
#

ohh.. okay..

summer stump
#

And maybe a ss of the console

opaque ibex
#

this is my code:

using UnityEngine;
using System.Collections.Generic;

public class PlanarGravityScript : MonoBehaviour
{
    public Transform atmosphere;
    public float gravitationalRadius = 10f; 
    public float gravitationalForce = 10f;   
    public Color gizmosColor = Color.red;

    void Start()
    {
        Physics.gravity = Vector3.zero;
    }
    void Update()
    {
        Collider[] colliders = Physics.OverlapSphere(transform.position, gravitationalRadius);

        foreach (Collider collider in colliders)
        {

            Rigidbody rb = collider.GetComponent<Rigidbody>();

            if (rb != null && rb != GetComponent<Rigidbody>())
            {
                Vector3 direction = transform.position - collider.transform.position;
                float distance = direction.magnitude;
                float gravityStrength = gravitationalForce / distance;
                rb.AddForce(direction.normalized * gravityStrength * rb.mass);
            }
        }
    }
    
    void OnDrawGizmos() {
        Gizmos.color = gizmosColor;
        Gizmos.DrawWireSphere (transform.position, gravitationalRadius);
    }
}
opaque ibex
#

a moment... it's compiling my code

teal viper
#

Pro tip: always remove logs and other debug information in your code, so that people that help you can't guess what you have tried.

summer stump
opaque ibex
#

that's the only debug I have.

teal viper
#

I can see this code failing with compound colliders.

opaque ibex
#

what is that?... I have no idea what is compound colliders.

#

just used unity 2 weeks ago.

hoary kernel
#

why does my 3D Audio Settings not play when im in the range of it

#

help someone

opaque ibex
#

yeah... that's it. the root has rb and mesh collider

hoary kernel
#

why does my 3D Audio Settings not play when im in the range of it

opaque ibex
#

I thought at first it was the navmesh causing this problem but it turns out it's not

hoary kernel
#

help someone pls

#

cus this is so frustrating bruh

opaque ibex
hoary kernel
#

same

opaque ibex
#

I'm also asking for help here.

teal viper
spice sigil
#

Can anyone help me, I've been trying to see this code I made for 1 day because it's not going

it should appear in the inspector to be able to place the GameObjects but it doesn't appear, and this error appears

Assets/scripts/MudarCena.cs(24,12): error CS1520: Method must have a return type

eternal falconBOT
summer stump
#

Your method has no return type. Simple as that

#

Look at every other method you have, and then the one on line 24

hoary kernel
summer stump
#

Compare line 12, 18, and 30 (which are correct) to 24

summer stump
hoary kernel
summer stump
#

Absolutely irrelevant

spice sigil
hoary kernel
summer stump
hoary kernel
#

lol snitching ahh

hoary kernel
fickle plume
#

!warn 1160004646115475536 Don't spam the channel. Listen when people point out server rules.

eternal falconBOT
#

dynoSuccess apechasers has been warned.

polar acorn
hoary kernel
#

bro deadass thought he did sum pinging a mod

polar acorn
#

Glad to see I'm still able to detect problem children before engaging

hoary kernel
#

bro deadass your cringe as fuck

fickle plume
#

!mute 1160004646115475536 3d ignoring warnings, spam

eternal falconBOT
#

dynoSuccess apechasers was muted.

summer stump
#

I was gonna go answer there before the emotional breakdown
"Ahh" "cringe" "deadass"
Oof

frosty hound
#

They have a bunch of stickynotes with various one word slangs that can combine in various ways to get their thought across.

polar acorn
#

A markov chain trained at an elementary school

summer stump
#

Bible quote and gorilla tag clone link in their description and skibidi/toilet as pronouns.
Quite the collection haha

radiant frigate
#

how do i make a method that kills (setActive(false)) the player wait until an animation is finished?

#

if someone answer pls ping me in the message so i can read it,ty!!

teal viper
#

Does it have to be a method? If yes, then a coroutine(though it needs to run on an active and enabled object) or async method.
Otherwise a timer in update.@radiant frigate

radiant frigate
teal viper
radiant frigate
#

could you explain it again pls? i didnt understand it

teal viper
#

What part of it?

teal viper
radiant frigate
#

how can i make it wait for the animation?

#

i understand the words but i dont understand what you mean with them

teal viper
#

that's what the message explains: animation events or checking the animator state.

radiant frigate
#

okay

#

i guess ill go with the checking the animator state

#

ty!

small mantle
#

I am using the Navigation System, but want to know how I can adjust the pathfinding. I am making a TD game and don't want all the spawned Enemies to follow the exact same path. Currently I am using the agent.SetDestination() function.

teal viper
small mantle
#

I would like to dive deeper into the topic

teal viper
# small mantle Are there any videos on this topic? I have been searching but might not know the...

I don't think so. You'll need to read the docs and figure out a way that works for you.
Though it's not that difficult. The only actual navmesh related thing that you need to do is NavMesh.CalculatePath, though there are a few more functions that could come in handy for modifying the path correctly. That basically gives you an array of points.
From this point on, it's not realted to navmesh at all, you can move your character however you want along these points.

small mantle
hallow sun
#

How to change Terrain's material thru code?
unlike meshrenderer, name.material does not work

radiant frigate
#

how can i make a music slider that changes the value of an audiosource? my approach is to make a static audiosource and change its value to equal the slider one, but how could i reference the audisource?

devout flower
#

I heard that tasks aren’t really supported in webGl, but specifically multiple threads, i think
Would using await and then a custom task.Delay work? (Like using task.yield and time.time) Since some people say that it’s only Task.Delay that doesn’t work

queen adder
eternal needle
radiant frigate
#

didnt know there was one

#

will check right now

queen adder
#

but yea audio mixer is the more proper way to handle volume for sounds

#

not sure if the handles of audiomixer is exposed in the editor tho

radiant frigate
#

ty all!

queen adder
#

Hey! Trying to learn about how graphs work, but my script seems off. It's always printing "Left Click Value : False" regardless of if I have my right click button held down or clicked. Any ideas?

public InputActionProperty leftClickAction;
    public Animator cubeAnimator;
    void Update()
    {
        bool leftClickValue = leftClickAction.action.ReadValue<bool>();
        print("Left Click Value: " + leftClickValue);
    }```
#

I've tried using it as a bool and using it as a value, neither of which seem to work.

topaz mortar
#
{
    if (ItemSlots[i].transform.childCount > 0)
    {
        Debug.Log("Deleting item: " + ItemSlots[i].transform.GetChild(0).GetComponent<Item>().ItemData.Id);
        Item item = ItemSlots[i].transform.GetChild(0).GetComponent<Item>();
        DeleteItem(item);
    }
}```
What am I missing? I have 24 ItemSlots, only one which contains an Item, but if I trigger this function it triggers 10 times on the 1st and only item id?
queen adder
teal viper
steel stirrup
#

shouldn't that also be throwing out of bounds unless your collection si actually 1 indexed

queen adder
steel stirrup
queen adder
#

Ah right

#

for (int i = 0; i < ItemSlots.Count; i++)

steel stirrup
#

Also not sure why he isn't just using foreach here

topaz mortar
#
{
    //for (int i = 1; i <= InventoryData.ItemCapacity; i++)
    for (int i = 1; i <= 28; i++)
    {
        GameObject slot = Instantiate(inventorySlotPrefab, transform);
        slot.name = i.ToString();
        ItemSlots.Add(i, slot);
        EmptyItemSlots.Add(i);
    }
}```
#

the collection starts at 1

#

I had a foreach, but had the same issue, thought the regular for might fix it

steel stirrup
#

What is ItemSlots?

topaz mortar
#

private Dictionary<int, GameObject> _itemSlots = new Dictionary<int, GameObject>();

steel stirrup
#

What's your reasoning behind using a dictionary this way

topaz mortar
#

pretty sure this is one of those situations where I'm doing something extremely stupid, but just don't see it

topaz mortar
teal viper
#

Stepping through the code with a debugger might provide some clues. As well as confirming the objects in the hierarchy.

topaz mortar
#

let me try

teal viper
#

Ah, ok,I see the deleting one. But what are the others?

steel stirrup
#

This might be a silly question

topaz mortar
#

I added the itemslot name like someone suggested

steel stirrup
#

But did you check that your item ids arent duplicated?

teal viper
#

Maybe share the whole relevant !code correctly as we're just getting confused over nothing

eternal falconBOT
steel stirrup
#

Might also get more usable information by moving the debug out of the conditional so that it tells you what it did on each itemslot, that way you can check the overall flow

topaz mortar
#

ah found the cause, the function is just getting called several times because the event is thrown on Item
which throws it for each item in my game -_-

#

Alright fixed it 🙂
Moved the trigger to my Inventory and added a check to see if it's already deleting everything
Thx for the assist

loud mango
#
public class detectShoot : MonoBehaviour, IPointerClickHandler
{
    public GameObject flashPrefab;
    public GameObject muzzlePoint;
    private Rigidbody2D rb;
    public Rigidbody2D playerrb;
    public void OnPointerClick(PointerEventData eventData)
    {
        
        GameObject duped;
        duped = Instantiate(flashPrefab, muzzlePoint.transform.position, muzzlePoint.transform.rotation);
        
        Destroy(duped, 0.250f);
    }
}

can i use void Start() in this case? i wanna define rb of the duped object using getComponent

#

cuz defining it in the OnPointerClick will probably be more calculation thus lowering fps

steel stirrup
#

Don't quite understand the question. There's nothing there that wouldn't work in Start(), however you probably need to reconsider your overall structure because it's very unclear what you're trying to do

#

Is your goal to just have muzzle flash whenever a shot is fired?

#

Because in that case you should just be enabling/disabling the muzzle flash, not destroying and instantiating it

steel stirrup
#

If you have very high rates of fire with this approach it's going to become incredibly inefficient

loud mango
#

its getting duplicated after the 0.25s of animation is finished

steel stirrup
languid spire
loud mango
queen adder
#

You are constantly having to compute gameobjects being created and destroyed, as to it just dissapearing and reappearing

queen adder
loud mango
#

a cow cant shoot fast 😂

steel stirrup
#

Alright so think about the actual setup here and break it down

#

you have a gun

loud mango
#

wait imma try record and show you the exact problem

steel stirrup
#

The gun fires a bullet and has a muzzle flash

#

can the gun ever be firing more than one bullet at a time? No

#

Therefore there should only ever be one muzzle flash at a time

waxen aurora
#

I'm trying to swap materials to a specific object via script, the materials are made from a custom shader.
I have an "issue" where when replacing, unity generates instances instead of using the original so I fail to check if the current material is the same as the new one
Here's the code: https://pastebin.com/rKtZtc5s
Is this due to the fact that I assign the materials to handle in new temporary variables?

steel stirrup
#

Does the muzzle flash ever change in terms of position? Also, no, it's always attached to the end of the barrel

queen adder
# loud mango a cow cant shoot fast 😂

That's subjective.. There should only be one muzzle flash at any given time, you should just make it appear and dissapear. That's a lot of extra computing for no reason.

steel stirrup
#

Therefore, it's logical to just have a single muzzleflash attached to the end of the gun so you never need to worry about manually positioning it, worrying about rotation etc

#

IF you needed many objects, like lets say for bullets, then you also would never do it this way, you'd create an object pool and recycle the bullets as they leave the screen or otherwise expire

loud mango
#

i am gonna use raycast for the bullets

queen adder
steel stirrup
queen adder
#

Besides instantiating, what extra info does that give us 🤣

steel stirrup
#

we're not saying your way doesn't work, just that it's an incredibly inefficient way to do it

loud mango
#

the muzzle flash

#

its doesnt look good when it stays in one place and the player falls down

steel stirrup
#

because you're setting it up wrong

#

that's what we're talking about

queen adder
#

Do an animation then perhaps

steel stirrup
#

Just have a single muzzleflash and attach it to the transform

loud mango
#

so i wana set the velocity of the muzzle's rb to the player's rb

steel stirrup
#

Why does it have a rigidbody

loud mango
steel stirrup
#

The muzzle should not be a rigidbody

queen adder
steel stirrup
queen adder
#

Use a particle system perhaps?

steel stirrup
#

it'll follow the rb of the cow

#

This is like trying to control a swarm of agents by just giving them all the same orders and hoping they stay synced

loud mango
queen adder
loud mango
steel stirrup
loud mango
#

i just want it to fall down with the player.

queen adder
#

IT Doesn't look good WHEN it (the flash) stays in one place.. And the player falls down.

I'm taking that as it being locked to the front

loud mango
#

the rigidbody is just an idea

steel stirrup
#

because if its locked to the front, it will follow the player

#

by definition

steel stirrup
loud mango
steel stirrup
#

Don't instantiate anything

#

Just do it in the editor

#

Create your prefab, drag it to where you want it positioned and child it to the gun sprite

#

add a reference in your script

#

Where you're normally instantiating, enable it and where you're destroying, disable it

#

also disable it in Awake or Start in case you forget in the editor

queen adder
#

That causes issues when you fire fast though..

loud mango
#

what difference would it make? faster processing ?

steel stirrup
#

and this isn't a minigun

loud mango
queen adder
#

Clearly there is more than 1 flash on the screen at once

steel stirrup
queen adder
#

If you did that, it would suddenly appear and dissapear

loud mango
#

yeh, i had that problem in a different game

queen adder
steel stirrup
#

It looked like a single sprite to me. If its actually an animation, then you probably need to just setup an object pool

#

but you should still child them to the gun and get rid of the rigidbody

#

it's really two separate issues

loud mango
#

if i do the rigidbody thing and do flash_rb = player_rb then will it cause performance issues in reference to mobiles?

queen adder
# loud mango

So JOC IS THIS VIDEO how you WANT it to look like or is this showing what you DONT want it to look like?

#

Because that's what I don't get

#

The video fucked me

loud mango
steel stirrup
#

Then it needs to be childed, however you're then going to have an issue where they overlap

queen adder
#

You want it to be like stuck on the front?

loud mango
#

yeh

queen adder
#

But you also want the little fade out?

loud mango
#

ig, cuz i cant make particle system that looks good enough

queen adder
#

A particle system would be your best bet here I'm thinking lol

#

Then you don't have to deal with instantiating

loud mango
loud mango
queen adder
#

Couldn't you just set it to a billboard or stretch billboard render and rotate it to the proper position, and give it that same fire shit as a material? Idk haven't worked in 2D but I could get pretty much the same system.

keen night
#

Hello, i'm sorry if it's the wrong channel but I've got a mesh problem.
I've got a gameobject in my scene wth a meshfilter, but the problem is that I can't get the reference of this object

#

i can get it by code

#

but when i do a getassetpath it returns null

#

it should returns null only if it doesn't exist

#

but my mesh seems to exist...

#

I tried to do a Search in the project but didn't find, I've found the mesh ID in the scene file but idk what to do with it

queen adder
#

I don't think a mesh filter counts as an "asset" it looks like you are trying to find the filter rather than the mesh itself

loud mango
queen adder
#

oh THATS How you want it to work

keen night
loud mango
#

yeh, i am a really shit explainer

steel stirrup
#

If you want to optimize it, you can look into object pooling so you aren't constantly instantiating and destroying the prefabs, but probably not a necessity at the scale you're working

queen adder
#

Rather than instantiating maybe make 5 clones of it and activate them and deactivate them in loop o-o

loud mango
loud mango
#

thanks again to both of you

steel stirrup
#

It's not an issue of need, it will just smooth out your performance

steel stirrup
queen adder
#

No you're just activating and disabling objects, rather then having to create a whole new one.

steel stirrup
#

Instantiation is the expensive operation here

loud mango
#

well imma add them to the plan cuz i am now really bored of making the player cuz i am working on it for a week now

#

making things look good and smooth

queen adder
#

It's more of an optimize at every turn type of deal.. There's a lot of situations where crap hacks can solve problems, but those will start to add up. And you don't want to end up accidently using your crap hacks later on when you make a game where it matters.

steel stirrup
#

Object pooling is just kind of a basic thing you need to learn with Unity, even if it isn't absolutely necessary here. People tend to ignore it (or not realize it exists) and then they go and try to instantiate 500 buttons in a ui every frame

#

or create a bullet hell that's actually just a stress test of your RAM

queen adder
#

Ex. Pre line up 300 bullets, iterate through and set them to active and fire them. Instead of having a minigun that shoots like a mf and causes lag. (Again creating gameobjects is way more heavy than just working with ones that already exist)

loud mango
#

also did u like my game design? all cows are murdered by aliens in a farm except one. that cow makes a space ship using the tractor in the farm and fly to the alien's planet and from there, its a wave surviving game

queen adder
#

💪 Interesting

steel stirrup
#

I support cows

queen adder
#

Seems a bit odd why the cow would fly up there every time and practically kill himself with no way of winning but nice idea.

steel stirrup
loud mango
#

idk about winning, i can add it as a story so it defeats all bosses and then can have a endless mode

steel stirrup
#

trying to instantiate those bullets or missiles as needed would be a disaster lol

queen adder
#

Absolute

keen night
#

I've deleted EVERYTHING except the scene, but still got some meshes

#

i really don't understand

teal viper
keen night
teal viper
fervent abyss
#

in this vid id didnt happen tho

teal viper
#

That would make it stuck on top of the player if that's what you wish.

teal viper
#

Then explain what kind of behaviour you want

fervent abyss
#

im trying to phrase it right too :3

pallid nymph
#

detect squish - kill player 😛

keen night
fervent abyss
#

THIS IS A GREAT IDEA NGL ty for suggestion!!!

#

tbh actually why not

pallid nymph
#

it is a thing that some games do, if killing the player is a normal thing in the game

fervent abyss
#

killing is a part of my game :3

steel stirrup
loud mango
#

what shooting method should i use for ranged enemies? objects or raycast? if raycasts, how can i make it feel real

#

real as in that the player needs to know when the enemy is shooting or how to dodge the enemy

#

pls mention when replying

eternal needle
loud mango
eternal needle
# loud mango its pixel game

that doesnt really change anything about my answer. making it feel real is something u gotta consider in terms of game design. Like if there should be a chargeup sound/animation

loud mango
#

feel real as in

#

the player needs a sign that they have to dodge

eternal needle
#

or look at what other games do, though typically its just a chargeup sound/animation as i wrote above.

loud mango
signal tide
#

helllo guys I have a fps game where I have a imported a character model in which the body parts are not separable now when I try to attach hands of the player to the gun it looks fine but as soon as it jumps or runs it can see the inside of its body, for now I have just disabled player's body for local view so the gun is only there but is there any other way of doing it???

white sandal
#

Hi guys I have a quick question. I'm setting up my game by creating the characters and their corresponding HP bars but I'm afraid I'm assigning the components in a very wonky way, especially since I'm always using .Find() (especially in lines 46-51)

Would you say this is OK or do you recommend a different way of doing this? I'm a beginner so I'm unsure whether this is the right way to do this

Here's the code:
https://paste.ofcode.org/JZGCrG4DYvQ754PCiPiFNz

What do you think?

worthy tundra
#

do you think that its possible for navmeshagent to work with rigidbody?

wintry quarry
white sandal
pallid nymph
noble goblet
#

im trying to make a gun in 2d and the gun doesnt want to shoot only when i click it just keeps going and going and i dont know how to stop it

#

heres the code

#

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

public class shooting : MonoBehaviour
{
private Camera maincam;
private Vector3 MousePos;
public GameObject bullet;
public Transform bulletTransform;
public bool canFire;
private float timer;
public float timeBetweenFiring;
// Start is called before the first frame update
void Start()
{
maincam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
}

// Update is called once per frame
void Update()
{
   MousePos = maincam.ScreenToWorldPoint(Input.mousePosition);

   Vector3 rotation = MousePos - transform.position;

   float rotZ = Mathf.Atan2(rotation.y, rotation.x) * Mathf.Rad2Deg;

   transform.rotation = Quaternion.Euler(0, 0, rotZ);
   if(!canFire)
   { 
      timer += Time.deltaTime;
      if(timer > timeBetweenFiring);
      {
         canFire = true;
         timer = 0;
      }  
   }
   if(Input.GetMouseButton(0) && canFire);
  {
     canFire = false;
     Instantiate(bullet, bulletTransform.position, Quaternion.identity);
  }
}

}

sullen zealot
#

use GetMouseButtonDown(0)

ripe hill
#

why is there this random blue area in game view but not in scene view any solutions ?

wintry quarry
#

Reaching "down into" another object like that is poor practice.

sullen zealot
#

hello! i am trying to reference a script called "Movement" on instantiation but it doesn't work:
=====Spawner Script=====

Movement movement;
void Start()
{
  GameObject temp = Instantiate(Object);
  temp.GetComponent<ObjectScript>().Function(movement);
}

=====Object Script=====

Movement movement;

void Function(Movement movementHolder)
{
  movement = movementHolder;
}

is there a way to reference it in script without using the Find function?

wintry quarry
sullen zealot
#

how do i reference it

pallid nymph
#

[serializefield] private ...

sullen zealot
#

i cant use serializefield bc the object is a prefab that gets created during runtime

pallid nymph
#

you can on the spawner script, isn't that the idea?

#

and from there you inject it into the others?

sullen zealot
#

yes it referenced with serializefield

#

in the spawner

wintry quarry
white sandal
soft cloud
#

Im trying to make a version control collab project with my friend but despite adding them into the organization they cant seem to see the project or enter it any idea what i might be doing wrong

wintry quarry
# sullen zealot in the spawner

Ok then you have it and can pass it into ObjectScript with a function like in your example. Should work fine. But your example is not showing it as serialized so I'm confused

sullen zealot
sullen zealot
#

i also made it serialzefield in the object to see if the value changes during playtime but it remains null

wintry quarry
#

There's something wrong with how you set things up in the editor then, you'd have to show screenshots

#

But sharing your actual code is much better than some contrived example

muted narwhal
barren vapor
primal trench
#

how do i change a image's width in code?

ornate lynx
#

hello, i'm trynna make my own acceleration and decceleration script for a 2d character controller. and for some reason, when i'm going to the left, the character sort of goes back a little when i release the arrow key.

wintry quarry
#

Also how is dir set?

ornate lynx
wintry quarry
#

Dir is going to be either -1 or 1 depending on which way you press

ornate lynx
#

yeah but if i don't press, it's going to be 0

wintry quarry
#

Oh you're right

#

But your logic with the+= is still wrong

ornate lynx
#

sooo why is the character going back when i go to the left and release the arrow key? it's working properly when going to the right

ornate lynx
wintry quarry
#

You should be using Mathf.MoveTowards instead of this jankiness

#

Otherwise properly account for the direction you're moving

ornate lynx
#

i tried movetowards before and...idk how it works

wintry quarry
#

Because you can't just blindly add or subtract, that will only work in one direction

#

Your code right now assumes that deceleration is always to the left and acceleration is always to the right

ornate lynx
#

soo i just can implement this?

speed = Mathf.MoveTowards(rb.velocity.x, _maxSpeed, 0.3f) * Time.deltaTime;
wintry quarry
#

No

ornate lynx
#

so how?

wintry quarry
#

More like speed = Mathf.MoveTowards(speed, dir * maxSpeed, Time.deltaTime * .3);

ornate lynx
#

can i just do Mathf.Sign(dir) cus i wanna deccelerate instead of stopping right away

river quiver
#

how do i make the script disabled when the scene is loaded, but then i can enable it from a different script by a function

wintry quarry
#

Or rather acceleration

#

That's what MoveTowards does

ornate lynx
#

if i were to draw the curve it makes, what will it look like?

wintry quarry
#

An acceleration curve

ornate lynx
#

so it's not linear?

#

like...is it kinda like an exponential curve?

wintry quarry
#

Acceleration is constant
Velocity is linear
Position is quadratic

#

Depends which chart you look at

ornate lynx
#

i'm talking about the character's speed

#

so velocity

#

ok ok i will try to implement this

wintry quarry
#

hoenstly the line of code I shared is pretty much the entire function

#

the only missing part is assigning the velocity.

ornate lynx
#

yeah the rest of the conditions are useless i just found out

wintry quarry
#
speed = Mathf.MoveTowards(speed, dir * maxSpeed, Time.deltaTime * .3);
rb.velocity = new(speed, rb.velocity.y);```
#

the only other bit would be handling a different "deceleration" rate vs "acceleration" rate

#

if desired

ornate lynx
#

yes

#

thank you, i'll let u know if i got both working

wintry quarry
#

so like...

float rate = dir == 0 ? .1f : .3f;
speed = Mathf.MoveTowards(speed, dir * maxSpeed, Time.deltaTime * rate);
rb.velocity = new(speed, rb.velocity.y);```
ornate lynx
#

uhhh, give me a sec

#

isn't movetowards a little slow?

ivory bobcat
#

How so?

cosmic dagger
#

that should depend on your rate of change in movement . . .

ornate lynx
#

yeah yeah i landed on 50 for acceleration and 70 for decceleration, so i'm good now

#

just need to make the code look better cus it looks like it's made by a beginner which i'm definitly not

worthy tundra
signal tide
#

is there any way to edit single mesh renderer characters?
ps. I have a character and I want to detach my characters hand from the body but it has only one mesh so I'm not sure hot to do it

eager spindle
#

cant

#

youll need to open it in blender or smth

#

you can use the animation tool to move the hand but it wont detach, only stretch

smoky granite
#

guys i have a mouse position code that converts the mouse position to vector3 and its literally doing nothing does anybody have any ideas?

here is the code:
public Vector3 GetMouseWorldPosition() { return camera1.ScreenToWorldPoint(Input.mousePosition); }

slender nymph
#
  1. it's three backticks for code blocks, not just one. you'd think after the number of times you've made this mistake you'd get it at this point
  2. "literally doing nothing" isn't very descriptive
  3. https://unity.huh.how/screentoworldpoint
smoky granite
slender nymph
#

what Vector3 did you make public? because you aren't assigning anything in the code you showed

smoky granite
#

the GetMouseWorldPosition

#

hold on i'll send the whole thing

slender nymph
#

that is a method not a variable. it can't appear in the inspector

smoky granite
#
public Camera camera1;


public Vector3 GetMouseWorldPosition()
{
    return camera1.ScreenToWorldPoint(Input.mousePosition);
}

private void OnMouseDown()
{
    
    mousePositionOffest = transform.position - GetMouseWorldPosition();
    
}

private void OnMouseDrag()   
{
    transform.position = GetMouseWorldPosition() + mousePositionOffest;
}```
#

i did it

#

as in code block

#

not the thing lol

slender nymph
#

have you actually confirmed that any of these methods are actually being called

smoky granite
terse plume
#

does IObjectPool has a "safety check" method?
What happens if somebody returns an already destroyed object? 🤔

slender nymph
#

why would you be putting destroyed objects into your object pool?

terse plume
#

you shouldn't, exactly 😅
I want to know if there is a safety check or just a cryptic crash the next time you get that item from the pool 🥲

#

I guess I could crash myself on the Release action 🤔

smoky granite
#

tried debug logging and no they are not

summer stump
smoky granite
#

i dont see how though?

slender nymph
terse plume
polar acorn
terse plume
smoky granite
#

i'll get just a square hold on

polar acorn
#

So, it probably won't blow up your entire program, but it's also definitely not something to try to test the limits of

smoky granite
#

i have an idea hold on

slender nymph
smoky granite
#

i might be using the wrong input system

slender nymph
#

if you are using the Input System rather than the input manager that would also be a reason why it isn't being called

#

use the event system interfaces like the IPointerDownHandler interface

smoky granite
smoky granite
slender nymph
smoky granite
#

i also have another idea but im not sure if it would work, if i used if statements would it work?

slender nymph
#

if statements aren't going to magically make OnMouseDown be called if the conditions for it being called are not met

polar acorn
slender nymph
#

what worked

smoky granite
#

well instead of using that void OnMouseDown() i did an if statment in the void Update() but doing the exact same thing and its now updating the moueposition

#

which i know also means instead of picking something up this will instead make it teleport to the mouse but that works better for what i actually wanna use it for

#

holy shit wait

#

fixed everything its all done everyone here kiss me i'd like to thank my family, friends and the people who helped me along the way

dreamy panther
frigid quartz
#

This is a stupid question, and I understand somewhat insignificant but hey, this is the beginners section...
Does it make sense to name a script "SceneSystem"? I want the script to be ran across all scenes, and I want it to only be responsible for loading different scenes when triggered by events? I know SceneManager is already taken by Unity, and "LevelManager" per TaroDevs tutorial doesn't seem like a fitting name for my project

cosmic dagger
frigid quartz
polar acorn
dreamy panther
frigid quartz
cosmic dagger
# frigid quartz Oh, yeah that's a better name. Thank you 🙂

also, you can use SceneManager, just create your own namespace

namespace Immortal
{
    public class SceneManager : MonoBehaviour { }
}```
honestly, be defeault, you should use (have) your own namespace. this prevents conflicts between your classes and others' . . .
cosmic dagger
frigid quartz
willow scroll
#

I suppose, not many people, including me, create their classes in namespaces in Unity. So, your PlayerController, GameManager etc. usually don't refer to any namespace

#

When having another functionality, for example, a full assistance scope, which should not interfere with the main game management, I would consider creating a new namespace. But this is just my opinion

polar acorn
#

I don't tend to use namespaces at all personally. Granted, I do use Assembly Definitions, which is also a form of code compartmentalization, but I don't tend to use custom namespaces in addition to that

frigid quartz
willow scroll
upper tide
#

Is it impossible to get a component of a gameObject's component set in editor, in the Start function of a script?

willow scroll
polar acorn
upper tide
#

Gotcha

willow scroll
upper tide
#

atwhatcost I'm a bit dense in the head forgive me

summer stump
upper tide
#

Aye aye

river quiver
#

how do i make the script disabled when the scene is loaded, but then i can enable it from a different script by a function

polar acorn
river quiver
#

its in the scene

#

the script i want to disable is on the camera

polar acorn
#

Uncheck the box next to the script on the object

river quiver
#

it was that simple lol

polar acorn
#

Yep, a disabled script can still be referenced and enabled like any other, it just means Unity functions like Start and Update don't work, but you can call functions manually

river quiver
#

thats exactly what i was going for, cause when i tried disabling the script by this.enabled = false; in the first line of the Start function it didnt work and the function was still called

summer stump
#

But yeah, when possible do it via inspector

river quiver
#

yeah i just realised i have to change it to awake cause when i disable the function and then enable it again the start method doesnt run

summer stump
#

Yeah, start (and awake) only ever execute one time in the objects entire lifetime

#

There are OnEnable and OnDisable though, which run EVERY time it is enabled or disabled respectively

river quiver
#

thanks

mint remnant
#

are you asking why text messages are limitied in size?

muted narwhal
#

No, why is text ends abruptly?

#

It should go to the next line once it reaches the "end" of parent?

#

But it's just goes to the next line whenever it wants

fickle plume
#

@muted narwhal Don't cross-post, instead provide more information in #📲┃ui-ux so it can actually be answered.

muted narwhal
#

I'm sittin' there for 5 hours

grave furnace
#

guess i'll make my first state machine

#

hope thats not too hard

fickle plume
mint remnant
grave furnace
#

the process of coding a state machine?

#

or the states i want to create?

mint remnant
#

a state diagram circles and lines

grave furnace
#

oh no idea whats that, i need some research

#

i mean

#

i know what are diagram circles and line but idk how exactly a state machine works

#

i just know i need it rn

mint remnant
#

can be as simple as a case switch statement

spiral glen
#
using System.Collections.Generic;
using UnityEngine;

public class moveScreen : MonoBehaviour
{
    Rigidbody2D rb;
    public float speed = 5;
    float inc = 0;
    void Start(){
        rb = GetComponent<Rigidbody2D>();
    }
    void Update(){
        float inputx =  Input.GetAxis("Horizontal");
        float inputy =  Input.GetAxis("Vertical");
        Debug.Log(inputx);
        Debug.Log(inputy);
        while(inputx > 0 || inputy > 0){
            inc = inc + 0.1f;
        }
        rb.velocity = new Vector2(inputx * (speed + inc), inputy * (speed + inc));
    }
}

anyone know why this is causing my code to crash (it started when I implemented the inc value)

#

nvm I'm foolish

wintry quarry
#

a while loop is pretty inappropriate here anyhow

spiral glen
#

wy

#

why's that

wintry quarry
#

what's the intent with a while loop here

#

a loop inside Update is going to finish entirely within a single frame.
When you want something to happen over the course of several frames, Update itself is the loop you want

spiral glen
#

to constantly check if my inputx or inputy is more than (or eventually less than) 0 so I know when the palyer is moving

wintry quarry
#

Update runs every frame

spiral glen
#

ah

wintry quarry
#

you don't want or need an additional loop

spiral glen
#

so if would be better

wintry quarry
#

I don't see what the poiint of "inc" is at all

#

so it's hard to say

#

it doesn't make sense

spiral glen
#

make the movement faster the longer you move for

wintry quarry
#

but you're never resetting it

spiral glen
#

I was gonna reset it after I finished implementing the speed increase

wintry quarry
#

I would expect something like:

    float inputx =  Input.GetAxis("Horizontal");
    float inputy =  Input.GetAxis("Vertical");
    Vector2 input = new(inputx, inputy);
    if (input.magnitude > 0) {
      inc += Time.deltaTime * acceleration;
    }
    else {
      inc = 0;
    }

    rb.velocity = input * (speed + inc);```
spiral glen
#

what's .magnitude

wintry quarry
#

the magnitude of the vector

spiral glen
#

ah ok

#

that should of been obvious

spiral glen
#

just minus the whole time.deltatime * acceleration

wintry quarry
#

That's a very complicated if statement

spiral glen
#

it works tho

wintry quarry
#

Also you're missing deltaTime which you will need if you want this to be consistent at different framerates

spiral glen
#

oh ok

wintry quarry
#

realistically this code should live in FixedUpdate too

spiral glen
#

what's the difference

#

I'll google it actually

#

I forget google is a resource sometimes

#

fixed version of update, wow

spiral glen
#

or is that only for vector3

eager spindle
#

we're comparing input.magnitude. it's how big the vector is

#

input is a vector, input.magnitude is a number

spiral glen
#

that makes sense, thanks

wintry quarry
eager spindle
#

fun watch

spiral glen
grave furnace
spiral glen
#

wouldn't it be in the animation channel

grave furnace
#

not really, im not animating anything for this thing i'm trying to code

#

its literally three squares

spiral glen
#

probably game design then

grave furnace
#

kk

#

thxx

mint remnant
#
    void Start()
    {
        mesh = new Mesh();
        GetComponent<MeshFilter>().mesh = mesh;
        StartCoroutine(CreateOrModifyMesh()); // alters triangels, such as hiding a face
    }

    void Update()
    {
        UpdateMesh();
    }

    private void UpdateMesh()
    {
        mesh.Clear();
        mesh.vertices = verticies;
        mesh.uv = uvs;
        mesh.triangles = triangles; // is this when drawcalls are made?
        GetComponent<MeshCollider>().sharedMesh = mesh;
        mesh.RecalculateNormals();
    }

Is this a valid approach to making a dynamic mesh and the comment about drawcalls is that correct?

#

Also should I semiphore the updateMesh call to ensure the createOrModify step is fully completed?

wintry quarry
#

GetComponent<MeshCollider>().sharedMesh = mesh;
This is not necessary to do every frame

#

should I semiphore the updateMesh call to ensure the createOrModify step is fully completed
Maybe? It's not clear what that coroutine does in the first place.

mint remnant
#

It essentially builds the array of verts, triangles and uvs, I would also in that process do things like remove hidden faces

wintry quarry
#

What's the relationship between that and your UpdateMesh function?
Why does UpdateMesh run every frame?

#

Are you expecting everything to change each frame?

grave furnace
#

is there a difference between state machine and finite state machine?

wintry quarry
mint remnant
#

I was thinking if the triangle array changed not in size, but in values I'd have to reassign it, but I suppose I wouldn't have to per what you're saying

wintry quarry
#

Well first off are you expecting that to happen?

#

but no, you don't have to do that

#

The renderer already knows which mesh to render

mint remnant
#

THis is basically a minecraft style chucnk of voxel that I coudl "dig" into

wintry quarry
#

You only need to run it when things change

#

runing it every frame is wasteful

mint remnant
#

Makes sense, I was thinking if the traingle data changed, but now that you say it sounds legit

#

mesh.RecalculateNormals() I assume would be a good thing to call in the updateMesh

wintry quarry
#

yes in UpdateMesh, but not in Update

mint remnant
#

thanks much for the insigfhts

fading mountain
#

is there a way to load the chronological last scene in the build settings?

errant pilot
#

Guys how can i get a list or array of all objects colliding with a boxcollider?

rocky canyon
#

then add to the list..

#

OnCollisionExit -> check if its in the list -> remove it

errant pilot
#

ill try it thank you

noble goblet
#

yo i wanted to make a shooting script for 2d but the player just keeps shooting and doenst stop even if i click my mouse and i wanna make it shooti only when i click can anyone help me

#

thats the code

rocky canyon
#

!code use formatting or paste bin for big code blocks like so

eternal falconBOT
noble goblet
modest dust
#

As the bot tells you to do

#

Wrap your code with
```cs
// Your code
```

noble goblet
#

kk i fixed it

modest dust
#

If you're using a paste site, make sure you select C# highlighting

#

Right now it's just a white wall of text

noble goblet
#

wym like the ``cs?

modest dust
#

No, it should be somewhere on the paste site

#

A drop-down with all language highlightings

raven trench
#
    public float sensY;

    public Transform orientation;

    float xRotation;
    float yRotation;



    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    // Update is called once per frame
    void Update()
    {
        float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
        float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY;

        yRotation += mouseX;

        xRotation += mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        transform.rotation = Quaternion.Euler(xRotation, yRotation, 0f);
        orientation.rotation = Quaternion.Euler(0f, yRotation, 0f);

this is my camera controller that i made form basic tutorials and such, but when i move my mouse down it looks up how do i invert that

#

i thought i just had to swap smt but i been testing stuff out and i am NOT gettin it

rocky canyon
modest dust
rocky canyon
#

soo just negate the value

raven trench
#

alr ty 🙏

modest dust
#

Yep

noble goblet
#

alr ty

modest dust
primal trench
#

how would i enable and disable hide in editor for a variable on the fly?

modest dust
#

And try to debug what's going on, place a Debug.Log where the timer get's cleared and where the bullet is fired

noble goblet
modest dust
#

Also

cosmic dagger
modest dust
#

Is there any error in the console?

noble goblet
primal trench
modest dust
polar acorn
slender nymph
#

or use an asset like NaughtyAttributes or OdinInspector which both have that functionality

noble goblet
polar acorn
primal trench
modest dust
slender nymph
noble goblet
modest dust
#

But basically, Debug.Log("hello", gameObject); would print "hello" in the Unity console and clicking the log would point you to the specified gameObject

#

Second param is optional

#

But useful

random furnace
#

So basically I have a ready function but I want it to be activated on a trigger. But I want the script to check if the player is touching the trigger of ANOTHER object and not the the object where the script it. How do I refference it?

polar acorn
raven trench
#

in my code i have the sprint set up so when you hit a button switches your state to sprinting yknow simple enough, but how do i go about making the increase in speed not instant and like a increase over time thing

#

like instead of just goin straight from 5 to 10 the number would gradually increase over a second or two

#

is it a complicated thing or is there a simple way to do it

errant mesa
#

Hi, when i use my arrow keys to move my rigid body, it moves forward but when i use the exact same rb.addforce() when a button is clicked, it moves sideways, how do i fix such

rocky canyon
#

Lerp, or SmoothDamp, or MoveTowards, or some other method..

if(running){speed = (Lerp to Run Speed);}
.. then farther in the code
movement * speed

raven trench
#

alr ill try workin that in

rocky canyon
#

i set desiredSpeed to be one or the other.. (w/ smoothing inbetween) and just use my desiredSpeed in my Movement function

rocky canyon
raven trench
rocky canyon
#

yes. that'd end up being an extra variable u can fine-tune to make ur player adjust its speed faster or slower

raven trench
#

alr thank you

rocky canyon
#

i call mine momentumSmoothing

misty pecan
#

Having a problem where bullets hit multiple enemies when theyre close together even though they are scripted to be destroyed upon colliding is there any fix?

#

2D

rocky canyon
# raven trench alr thank you
using UnityEngine;

public class SmoothMovement : MonoBehaviour
{
    public float walkSpeed = 2.0f;
    public float runSpeed = 6.0f;
    private float desiredSpeed;
    public float momentumSmoothing = 10.0f;
    private float currentSpeed = 0.0f;

    void Update()
    {
        if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
        {
            desiredSpeed = runSpeed;
        }
        else
        {
            desiredSpeed = walkSpeed;
        }

        currentSpeed = Mathf.MoveTowards(currentSpeed, desiredSpeed, momentumSmoothing * Time.deltaTime);
        transform.Translate(Vector3.forward * currentSpeed * Time.deltaTime);
    }
}
``` something like this
raven trench
errant mesa
rocky canyon
#

well, are they oriented the exact same?

#

transform.forward could be two different directions dependin on its transform

real falcon
#

I'm looking for a way to clamp or constrain a vector to another vector with some variation

#

so like if a character is facing forward, I want to move a vector towards something, but only so much

#

and if the character turns that vector would be able to turn with it

polar acorn
#

When you say "move a vector towards", do you mean rotation or displacement?

real falcon
#

rotation

#

I will show the code I have now

rocky canyon
#

wouldnt that just be a local Rotation?

real falcon
#
    {
        // The step size is equal to speed times frame time.
        float singleStep = rotationSpeed * Time.deltaTime;

        if (constraintVector != Vector3.zero)
        {
            // Get the angle difference from constraint
            float angle = Vector3.Angle(targetDirection, constraintVector);
            

            float rads = Mathf.Max(maxDegrees - angle, 0);
            if (showLog) Debug.Log(angle + "   R " + rads);

            // Convert to radians
            rads = (rads * Mathf.PI) / 180;
            //Debug.Log(angle + "   R " + rads);

            singleStep = Mathf.Min(singleStep, rads);
        }

        Vector3 newDirection = Vector3.RotateTowards(startVector, targetDirection, singleStep, 0.0f);
        newDirection.y = 0;
        //Debug.DrawRay(transform.position, newDirection, Color.red);

        // Calculate a rotation a step closer to the target
        return newDirection;
    }```

the issue I have now is that it doesn't work as I intended, if the target direction is too far outside it just completely stops rather than keeping up with the contstraint vector
real falcon
summer stump
real falcon
#

the issue is I need the max rotation to depend on how far its already angled away from a target vector

#

I thought I had the solution but I didnt

#

and now im lost

errant mesa
rocky canyon
#

🤔 debug the values u use like Aethenosity asked

real falcon
#

I need the blue vector to be able to move within the red cone defined by the red vector, while being clamped inside when it gets to the edges of that "cone"

polar acorn
errant mesa
rocky canyon
#

on both versions

#

and post up the results of the console

real falcon
#

I have an enemy which basically can look around, but can also rotate its model

#

I want it to look quickly but rotate slowly

#

and not be able to look directly behind itself

#

I tried getting the angle between the desired rotation and the constraint/red rotation, but I haven't found a way to properly use it

#

I need the max radians to basically find how much it can move until it hits the "border" of that max angle from its base

pallid nymph
#

is the cone vector thing 2D?

real falcon
#

yeah so like

mint remnant
#

have you looked at vector projections or vector components?

real falcon
real falcon
#

imagine like a tank and the red vector is the direction of the base vehicle

#

and the blue is the barrel

#

the barrel can move faster, but can only rotate so far relative to the base

pallid nymph
#

so, it's an actual 3D cone? and you have the red vector and you only want to move the blue one to (for example) 15 degrees or the red one if it goes above 15 degrees?

real falcon
#

yeah I want it to be constrained within x degrees of the red vector when it tries to move

#

like how you can move your head quickly but can't look behind you

#

you can only move your head so far before you need to turn the rest of your body

#

but I can't find out how to get the "max radians delta" based on the red vector

pallid nymph
#

you can probably do something like getting angle between the 2 and if it's above X, you subtract from the angle you got, you get a cross product of the 2 vectors and you rotate around that axis with that subtracted angle (or minus that angle, I can't math that well 😄 )

real falcon
#

so getting the angle between the current blue and the red

#

and then subtract what?

pallid nymph
#

X, if the angle is above X

#

that'd be the amount you need to bring it back

#

oh...

#

or...

#

if angle above X, you get that cross product and rotate the red vector X degrees around that axis

real falcon
#

no the red does not rotate

#

well, not here anyways

#

the red has a fixed speed

pallid nymph
#

well, that'd be to get the constrained blue

#

I'm not saying to actually move the red one, just rotate it X degrees around that axis - that's where blue should be

true siren
#

Is there a way to scale the game to different screen sizes properly?

I have tried ways but they all increase / decrease the distance between objects or zoom super in or out which affects gameplay.
I want each player to have the same experience

real falcon
#

the cross product is a vector right

#

is it the one that points perpendicular to the plane created by the other two