#💻┃code-beginner

1 messages · Page 397 of 1

wintry quarry
#

this will not fly forever unless you have disabled gravity

mild onyx
#

what i mean is i can spam the space bar and it will keep going up, i want the space bar to not work until i touch the floor again

ivory bobcat
#

Are you referring to not having any extra motion simulated relative to your velocity you've added?

mild onyx
#

this is my first time with c# and i know NOTHING

wintry quarry
#

You should find and follow a basic tutorial.

#

any basic tutorial will cover this

mild onyx
wintry quarry
#

what did you expect

#

find a different one

ivory bobcat
stuck palm
#

can you not serialise vector3's?

mild onyx
#

ik i thought i could steal stuff but so far c# seems alot harder than pyhton, then again i never coded a game in python

wintry quarry
#

how did you install newtonsoft JSON

ivory bobcat
stuck palm
stuck palm
wintry quarry
stuck palm
# wintry quarry can you show your code
void SaveReplay()
    {
        string json = JsonConvert.SerializeObject(_replay, Formatting.Indented);

public class Replay
{
    public List<ReplayPlayer> _replayPlayers;
    public LevelEnum level;
    public List<GameState> stateList;
}

[Serializable]
public struct GameState
{
    public List<Vector3> playerPositions;
    public List<Vector3> playerVelocities;
}

I'm just tryna serialise this object

wintry quarry
#

it tries to serialize properties by default

ivory bobcat
stuck palm
wintry quarry
# stuck palm how can i avoid that

Well typically I carefully curate all the objects I'm serializing with newtonsoft and use the "OptIn" approach as such:
https://stackoverflow.com/a/55046228

If you really want to reuse builtin types like Vector3 it gets more complicated

#

so rather than serializing Vector3 - I would make my own serializable Vector3 with the appropriate annotations. And perhaps an implicit conversion operator between them

#

so I'm a little confused why it's not working

stuck palm
wintry quarry
#

I just though thtese converters were iincluded with the UPM package but maybe not?

#

I guess maybe the UPM package doesn't include this by default so you have to add it

stuck palm
wintry quarry
stuck palm
ivory bobcat
stuck palm
wintry quarry
#

the converters package is separate

peak python
#

hi, not sure if it is a beginner or advanced,
I am used to building 3d games with physics, like golf for example.
Now i am trying to build a simple 2d game where you can drop items that destroy ground and move car from left to right.
The thing is, i am trying to make ground to behave like sand - so if i destroy the ground, it would be filled from the sides ( like sand ) but it would become uneven, so i want it to behave like fluid, but not as water.
My first though was to make a bunch of square bodies, and when i drop the item that destroys ground in radius x - just get all the bodies that are withing radius and delete them - making unity physics engine do its thing, but, i am afraid it would tank the performance and that car movement from left to right would become unstable (because of wonky physics considering large amount of small square bodies that make the ground)
Or there is already a premade sand ground that i can use, that i didn't find.

mild onyx
wintry quarry
ivory bobcat
stuck palm
peak python
#

oh wait, i can just give them gravity speed, no need to loop over thinksmart

peak python
#

this should make it easier on the cpu, since the only processing would be when it is going down - which is simple gravity

stuck palm
#
[Serializable]
public class ReplayPlayer
{
    public CharacterEnum character;
    public int characterColor;
    public int characterID;
    [JsonIgnore, SerializeField] public PlayerInputController inputController;
    public bool isReplay;
    public int frameLength;
    public List<InputPacket> InputPackets;
}

Does jsonignore not work with the new converters?

wintry quarry
#

JsonIgnore should work fine...

wintry quarry
cyan folio
#

In the animator I made a transition from Entry to Walk but there are no parameters. Can anyone please help?

polar acorn
noble reef
#

how do I add an overhead ui to an object when i have my mouse over the object

eternal needle
teal viper
noble reef
#

whats a world space cnvas

teal viper
#

A canvas set to render in world space.

#

Check the canvas page in the manual to learn how it works

noble reef
#

can u send me the link to it

eternal needle
teal viper
#

It's really easy too. Just type: "unity canvas manual" in google and hit enter.

noble reef
#

oh i thought it was somewhere in unity

teal viper
#

It is. In unity manual. And you google to find the link.

weak talon
#

the conveyor on left, if yo ucan see the ores just get stuck
and conveyor on right the ores somehow dont get stuck
idk why this is happening can anyone help?

summer stump
violet elbow
#

Hi everyone,

I encountered an issue with items after saving and loading in my game, and I need some help.

I am trying to save itemStateData at the end of each day by calling the Save() method, which saves the data to a JSON file. When the game loads, it retrieves the item states from the JSON file. However, after loading, the items on the ground can no longer be picked up.

Here is the relevant code:
https://gist.github.com/Cindylanlan/06a9ec8bbe64ad227bc5c3e1a7c126b1

Can anyone help me figure out why the items on the ground cannot be picked up after loading the game? Thanks a lot!

Gist

ItemStateData.cs// SaveLoadSystem.cs // ItemManager.cs - gist:06a9ec8bbe64ad227bc5c3e1a7c126b1

weak talon
# summer stump You need to provide something actionable

i dont know what else to write about it,

private void OnTriggerStay(Collider other)
{
    if (other.gameObject.CompareTag("Ore"))
    {
        rb = other.gameObject.GetComponent<Rigidbody>();

        Debug.Log("DAOWJID");
        rb.velocity = (conveyorDir.transform.forward * conveyorSpeed);
    }
}

that is my conveyor code
where if it collides with gameobject tag ore then it sets velocity, i have no idea why it doesnt work on one side of conveyor but works on the other

weak talon
summer stump
weak talon
#

this is the prefab

#

and this is in inspector

summer stump
#

I wonder if it is the fact that it is a box collider. Catching on the conveyor.
I assume that is a box as well?

weak talon
#

there is a collider that is set to is trigger and that is the one sticking out the top and another for the actual conveyor which is on the black box

#

its extrra weird because somehow the dropper on the right is working and not getting stuck
but dropper on left is getting stuclk

#

i think it is just a chance thing because the one on the right got like one ore stuck

summer stump
#

I would try just making the non-trigger collider on the ore a squashed capsule. Scaled to be close to the box shape, but it will have rounded edges

weak talon
#

why does that just fix it, i dont understand

wind brook
#

very new here, I'm following a youtube tutorial and it's throwing me this error:

Assets\Grid.cs(57,1): error CS1022: Type or namespace definition, or end-of-file expected

my code is as follows:

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

public class Grid : MonoBehaviour
{
    Node[,] grid;
    [SerializeField] int width = 30;
    [SerializeField] int length = 30;
    [SerializeField] float cellSize = 1f;
    [SerializeField] LayerMask obstacleLayer;

    private void Start()
    {
        GenerateGrid();

    }
    private void GenerateGrid();
    {
        grid = new Node[length, width];
        CheckPassableTerrain();
    }

    private void CheckPassableTerrain();
    {
        for (int y = 0; y < width; y++)
        {
            for (int x = 0; x < length; x++)
            {
                Vector3 worldPosition = GetWorldPosition(x,y);
                bool passable = Physics.CheckBox(worldPosition, Vector3.one / 2 * cellSize, Quaternion.identity, obstacleLayer);
                grid[x, y] = new Node();
                grid[x, y].passable = passable;
            }
        }
    }

    private void OnDrawGizmos()
    {
        if (grid == null) {return;}
        for (int y = 0; y < width; y++)
        {
            for (int x = 0; x < length; x++)
            {
                Vector3 pos = GetWorldPosition(x,y);
                Gizmos.color = grid[x,y].passable ? Color.white : Color.red;
                Gizmos.DrawCube(pos, Vector3.one / 4);

            }
        }
        
    }
    private Vector3 GetWorldPosition(int x, int y)
    {
        return new Vector3(transform.position.x + (x * cellSize), 0f, transform.position.z + (y * cellSize));
    }
}
summer stump
weak talon
eternal needle
#

not the bottom

#

i only really noticed because i pasted it and saw the top most error as well

summer stump
#

Now that I knew what to look for, you have TWO methods with semicolons

#

I looked for that in the for loops (a common place) but skipped the methods

eternal needle
#

this also indicates your !IDE isnt configured, or you wouldve noticed some errors way earlier

eternal falconBOT
nimble apex
#
        if (GUILayout.Button("format json code", GUILayout.Height(25)))
        {
            string formattedData = JsonConvert.SerializeObject(event_data, Formatting.Indented);
            formattedData.Replace("\\","\n");
        }```
why this freeze unity editor?
rich adder
#

how large is the data ? also Replace returns a string

#

also why \\", "\n" ? shouldn't you format your json properly in otherway

nimble apex
# rich adder also why `\\", "\n"` ? shouldn't you format your json properly in otherway

ok so the UI here is a custom GUI made by my former team member
you put in json strings on the "text area", and fire up the events to make the UI work, how the UI work is not important, because it works well, the only question is you need to get in some json string, if the json string is too long and complicated , it will hurt ur eyeballs , because this UI will not do formatting, you need to do it urself if u want

#

the code above is what the formatting button does

#

and the result of ANY existing json formatting, either jsonutility, jsonconvert by newtonsoft, all turns the string into something like this

#

it does not implement indentation, but putting slashes to the string

#

this is what im trying to solve

#

but after 4 hrs of work, it seems that just by non-plugin codes or any approaches, u cannot format well json string in a text area UI

#

i think its time for me to step back and start another task

slender nymph
#

this is a unity server. try asking in the !cs server

eternal falconBOT
weak talon
#

hi
this isnt really a bug but i want to make my conveyor movement with the ore more realistic

right now with this code
private void OnTriggerStay(Collider other)
{
if (other.gameObject.CompareTag("Ore"))
{
rb = other.gameObject.GetComponent<Rigidbody>();

        Debug.Log("DAOWJID");
        rb.velocity = (conveyorDir.transform.forward * conveyorSpeed);
    }
}

it works on straight lines but when it turns it goes instantly and looks really fake.
This also makes the ore sometimes fall of the conveyor when turning and it is pretty annoying

anyone know how to fix this or make the conveyor movement more realistic and fluiudy?

i have tried rb.addforce but i dont know how it works and it just speeds up infinitely and slides of the conveyor and is way too fast

slender nymph
weak talon
slender nymph
#

i'd bet the issue is you overwriting gravity rather than "too low" gravity

weak talon
slender nymph
#

and if you are assigning to velocity anywhere and set the Y velocity to 0 then you keep overwriting the effects of gravity. for example this line rb.velocity = (conveyorDir.transform.forward * conveyorSpeed); assigns the velocity on the Y axis to 0 unless the object is pointing a bit up/downward

thorn fiber
#

Looking into making a radar for an RTS. Want to allow terrain/structure screening.

I considered raycasting for the most realistic option (casts following the animation of the radar dish) but I assume that's going to spiral out of control, performance wise. So I'm back to a massive trigger collider and raycasting only the unit-type objects within that. 1. Is my assumption correct? 2. Is there another way I'm not considering for this?

slender nymph
#

raycasting is fairly cheap

thorn fiber
#

I know it is per cast, but for a radar I need it to cast at potentially more than 360 degrees. As in, if the angles are too spread, it may not find things at distance. Is it cheap enough to handle something like 2-3 of these objects per player (lets say 4 players max for now) casting at about 720 rays a sec (each)?

slender nymph
#

profile it and find out

thorn fiber
#

hmmm, fair point. The casting method does open some functionality that I would have to fake in a trigger collider solution, so probably worth testing both.

#

Thanks!

keen dew
#

In general you can do several thousand raycasts per frame without any noticeable difference in performance

hasty sleet
# slender nymph profile it and find out

The profiler wasn't super intuitive when I tried to use it. I spun my wheels for a bit but it wasn't straightforward, and I was using the official docs as reference. Probably just a skill issue on my end, but other profilers I've used seem more doable

#

I'm crutching on an FPS counter right now. How regularly do you profile and how easy is it for you to interpret?

thorn fiber
slender nymph
slender nymph
hasty sleet
#

My friend has a relatively slow PC and is negatively impacting the input response time and causing camera jittering, but my PC can handle it. I'm running the profiler but it is unclear what should be focused on. My current approach is to tweak the execution order of camera rotation and player rotation

slender nymph
#

are you sure you aren't doing something silly like multiplying mouse input by deltaTime

hasty sleet
#

lemme check

#

I'm using Time.unscaledDeltaTime as a multiplier which is in the Update() loop

slender nymph
#

don't multiply mouse input by deltaTime, it is already framerate independent so doing that multiplication just makes it dependent on the framerate again and ends up causing stuttery camera controls

hasty sleet
weak talon
#

how do i fix?

when i click play it works, then when i click to place something the game just pauses

remote lynx
#

does the editor pause too?

#

or only game?

weak talon
#

just gasme

#

as if i just click pause

remote lynx
#

then you probably changed Time.timeScale to 0

weak talon
#

but i havent

remote lynx
#

check project settings -> physics -> Time Scale

#

when it pauses

weak talon
#

am i blind i cant see time scale

#

btw it like literatly pauses my game.
like the pause button at the top is blue

remote lynx
#

oh sorry its in settings -> Time

#

there is Time Scale

weak talon
remote lynx
#

can you send your code that places things?

slender nymph
#

check the console and make sure that there are no errors. if error pause is enabled then it will pause when an exception is thrown

weak talon
#

maybe it is inf loop
i changed 5 lines of code and basically swapped positions on 2 objects

slender nymph
#

an infinite loop would cause the entire editor to freeze

weak talon
#

hmm yeah

#

the blue button where you pause is clicked

#

and i cant unclick it

slender nymph
#

then stop ignoring the errors in your console

weak talon
#

i fixed it, the editor didnt freeze but there was a line of code that couldnt find the object because the tag waasnt on it, so i guess that is why it would pause

#

i dont know why it likje actually clicked the pause button and not freeze

swift epoch
#

It's default behaviour to pause on any error so you can inspect and debug when it occurs. You can turn it off in console window

weak talon
#

its annoying because it was working and now suddenly not

slender nymph
#

you have error pause enabled. when an exception is thrown the game will pause. this helps you inspect what is happening at the time an error happens

#

you should ideally leave it on and stop ignoring the errors that appear in your console

weak talon
#

ok yeah i fixed, just needed to make an if statement to make sure it doesnt try and find an object when it doesnt need to

peak python
#

to make 2d ground fall when ground below is removed, i think there isn't a way to do it in ok way other than make a script that pushes squares down and checks for squares below it to make sure to stop when it hits them.
Make ground out of n columns each having k squares, make lowest square line as ground to ignore the script. Freeze x and z axis for 2d
need to make sure that another rigid body can drive on top of this
i guess no other way than i described?

#

like this

#

found a video that shows what i want
https://youtu.be/TSBcXoaV0o0?si=5yIkrcHKWrUda5ki

In Tank Wars: Anniversary Edition, a player has to control a (stationary) artillery tank in order to take down opponents with ballistic shots from a selection of different weapons. We paired old school, pixelated, low-resolution 2D graphics with some modern-ish concepts and effects.
Download this game on steam: https://store.steampowered.com/ap...

▶ Play video
#

basically trying to recreate this but in unity and with movement 🙂

rare basin
#

how can I remove all bindings from a action (Submit action in my case), dynamically through code?

public class InputRebinder : MonoBehaviour
{
    public InputActionAsset inputActions;

    private void Start()
    {
        var uiMap = inputActions.FindActionMap("UI");
        var submitAction = uiMap.FindAction("Submit");

        submitAction.RemoveAllBindingOverrides();
    }
}
#

doesnt seem to work

strong wren
astral jungle
#

Why my editor thingys are invisible , they were working just fine before

slender nymph
#

Not a code issue. Try either resetting your layout (not sure if this will work) or restart the editor

peak python
#

might tilemap help with my ground thing?

#

because now with rigid body and collider with discrete collision, some of the ground parts just go through other partsnotlikethis

#

and i feel that having like 4000 rigid bodies is kind of too much

echo hamlet
#

I am having problems with animations with a wolf asset I downloaded (already rigged and animated) and just copied most of the components from the character from the third person controller series.
The problem is that it seems to be stuck
The animation doesn't seem to be playing because the blend tree just causes it to change between the start of each individual animation.
https://drive.google.com/file/d/1CLuitZqQNqP03R6un2nHqJdk3RYE7Rno/view?usp=sharing

swift crag
#

Is "Loop Time" checked on the animations?

swift crag
#

click on the model the animations came from, go to the Animation tab, and check "Loop Time" on each animation

stuck palm
#

@swift crag maybe the replay system should also replay the positions and velocities im storing? i feel like just inputs is not going to be enough at the moment.

swift crag
stuck palm
#

because some bs keeps happening and like a single event i cant determine will throw the whole thing out of whack

swift crag
#

you want to be able to accurately re-create the same game state on both sides by just sending inputs back and forth

stuck palm
#

i see.

swift crag
#

Sending positions and velocities over would mean that one player's game is controlling the other player's game

#

or...something like that

swift crag
stuck palm
swift crag
#

it won't be an error

stuck palm
#

i know

swift crag
#

it'll be something you did that is non-deterministic

stuck palm
#

im gonna have to look through all my shit and see what causes it

#

i have a video recorder that starts directly at the frame of starting and ends right as it ends, so i'll probably have to comb through some footage to see whats causing it.

swift crag
#

It could be that you're using RNG non-deterministically (how silly)

#

Unity may be using RNG for things like post-processing, for example

#

which would be framerate dependent

stuck palm
#

what about that seed thing you recommended?

swift crag
#

I think you're going to need to create your own RNG that's used strictly for gameplay

#

You also want to use a consistent RNG seed on both sides, yes

stuck palm
#

hm okay

swift crag
#

or use Unity.Mathematics.Random, which is a little closer to the UnityEngine.Random that you're used to

stuck palm
#

is there anyway to get like a callback or something whenever random is used?

stuck palm
#

zamn

swift crag
#

The problem with UnityEngine.Random is that there's a single static RNG state

#

You can save the current state, restore a different state, do some RNG calls, and then put the original state back

#

But that's a bit of a nuisance

swift crag
astral falcon
#

Arent the random values always the same depending on the seed?

ruby python
#

Hi all, really quick Scriptable Object question. Is it generally considered 'good practice' to use an SO to store data to persist data between scenes?

swift crag
#

The problem is that everyone uses the same global RNG state with UnityEngine.Random, so other code can interfere with your RNG state

stuck palm
swift crag
#

The trouble is that, like all other Unity objects, ScriptableObjects get unloaded if nothing is referencing them

#

this happens on scene changes

#

So if you write a value into an object and then change scenes, and nothing in the new scene references that object, the object gets unloaded

#

when you come back to a scene that does reference the object, it gets loaded again, and your changes are gone

swift crag
astral falcon
ruby python
swift crag
#

Just stick it in a static field or on a DontDestroyOnLoad'd object

swift crag
stuck palm
swift crag
#

This is one hell of a "general idea" here

swift crag
stuck palm
ruby python
peak python
#
using UnityEngine;
using UnityEngine.Tilemaps;

public class TilemapMovement : MonoBehaviour
{
    public float moveSpeed = 2f;            
    public Vector3Int moveDirection = new Vector3Int(0, -1, 0);   

    private Tilemap tilemap;                
    private Camera mainCamera;              

    private void Start()
    {
        tilemap = GetComponent<Tilemap>();   
        mainCamera = Camera.main;            
    }

    private void Update()
    {
        
        foreach (var pos in tilemap.cellBounds.allPositionsWithin)
        {
            Vector3Int localPlace = new Vector3Int(pos.x, pos.y, pos.z);
            Vector3 place = tilemap.CellToWorld(localPlace);

            
            TileBase currentTile = tilemap.GetTile(localPlace);

            
            if (currentTile == null)
            {
                continue;
            }

           
            Vector3 targetPosition = place + moveDirection;

            
            Vector3Int tilePositionBelow = tilemap.WorldToCell(targetPosition + Vector3.down);
            if (tilemap.HasTile(tilePositionBelow))
            {
                continue; // Skip this tile if there is a tile below
            }

            
            Vector3 viewportPos = mainCamera.WorldToViewportPoint(targetPosition);
            if (viewportPos.y < 0 || viewportPos.y > 1)
            {
                continue; // Skip this tile if it would go outside camera view
            }

            
            tilemap.SetTile(localPlace, null); // Clear the current tile
            tilemap.SetTile(tilePositionBelow, currentTile); // Move the tile down
        }
    }
}

i have this code that puts tile down when there are no non null tiles below it or if it is withing camera view
the thing is, it works for some tiles and doesn't for for others
my tiles are colored so there is no hidden tiles below the colored, thus i am not sure why this applies only for some tiles

#

and some tiles even go below the camera view

polar acorn
#

@faint lark moving here since it seems to be code related.

Do you have multiple instances of the Character class? Maybe any added at runtime that aren't in the scene to start?

peak python
#

and this is how the tile started

faint lark
#

so i dont understand why

polar acorn
# faint lark character class is a SO and all Character SOs have stats

The inspector will create a new stats class when you click on one if it's null. If you create a new Character instance outside of the inspector, stats never gets set to anything. You need to ensure that you are always setting stats to something upon creation, either by giving it a default value in code, or by having whatever creates the instance set it immediately after creation

peak python
#

is it because my code updates it without any delays? is this the case why tiles are not behaving like specified in code?

faint lark
#

thanks for the help

languid spire
peak python
languid spire
#

then I don't get what you mean by 'my code updates it without any delays'

peak python
#

I just don’t understand why some tiles overshoot and some undershoot when it comes to the falling down

#

Since they all are under the same logic of the script

#

I move them down by the y equals to the grid size

languid spire
#

Then you need to Debug your script

stuck palm
#
GameManager.Instance.RNG = new Random((uint)replay.randomSeed);

I'm trying to create a random with a seed that's grabbed from a json. why is the state different from the seed that is grabbed?

swift crag
#

If you've queried the RNG for a value, the state will change.

ionic zephyr
#

is it okay if I reuse the script of my inventory slots to create crafting slots or might it be really confusing?

modest dust
ionic zephyr
#

the inventory slots are the ones that keep track of what you have but for example have a max quantity of 30 items in each slot

ionic zephyr
#

think of Minecraft for example

#

those types of slots should be different scripts/classes?

modest dust
#

Then introduce a variable for a max stack size in your slot script if you haven't done it already

ionic zephyr
#

okay, thanks a lot!

modest dust
swift crag
#

You could define the "max capacity" in terms of both the number of items and in terms of a percent of the normal max stack size

#

that would be useful in many places

#

a crafting item slot can only ever hold 1 item

#

a small pouch can hold 1/2 of a normal stack

#

etc.

stuck palm
swift crag
#

I don’t know what your code is doing elsewhere :p

#

If you haven’t used the rng yet, then it should have the same state as the seed

fringe kite
#

why even if a raycast length is 0, this:

private bool IsGrounded() => Physics.Raycast(feets.position, Vector3.down, 0f);

still returns true and behaviours so weird

and when i test it on base colliders, like capsule, sphere, cube, this works perfectly, but with mesh collider doesnt

stuck palm
swift crag
#

Each time you query the RNG, its state updates.

stuck palm
#

I'm assuming if it stays the same then I'll just get the same number every time

swift crag
#

Exactly

#

The state is the only thing that affects what the RNG gives you

#

Nothing else matters

#

Hence it being the “state”

#

Your game also has a “state” — it’s just more complicated than one number!

astral falcon
#

!code

eternal falconBOT
vale bronze
#

can I ask a quick question about github here or should I join a dedicated github discord? it is somewhat related to unity

hallow iris
#

https://gdl.space/ocaqahetuf.cs detection script it is not properly working
https://gdl.space/cafoyidivo.cpp this is also not properly spawning bullets

i am trying to spawn bullets on a like 2d tile map within the fov in which the enimies are in but it is not working i have been trying for 6 hours to make this work please help

heavy kite
#

https://gdl.space/kegohitosa.cpp ,it makes me this error me this error "DialogueManager.cs(11,13): error CS0246: The type or name 'Actors' could not be found (are you missing a using directive or an assembly reference?
the only problem is that i don't understand why it makes me this error, i have rescerch but didn't find anything, it's a scrip which is normaly designed to create dialogue and work with an other script.
https://gdl.space/ejovijoloq.cs, this is the other script

dense crater
#

Hi I have a quick question, I’m trying to load a scene from assets in the editor but I can’t seem to find the right function to get all scene assets in a folder. Can someone point me in the right direction?

swift crag
#

Check AssetDatabase.FindAssets.

heavy kite
swift crag
#

I should ask why you're trying to do this, though

dense crater
#

I’m writing something that will only run in the editor

atomic bison
#

there is no channel for asking about unity and google play billing 6 right?

swift crag
#

actually, the former

dense crater
swift crag
#

this is about Google Play billing, not about a specific unity payment service

swift crag
#
foreach (var guid in AssetDatabase.FindAssets("t:Sprite ", new string[] { spritePath }))
{
    var info = new IconInfo() {
        sprite = AssetDatabase.LoadAssetAtPath<Sprite>(AssetDatabase.GUIDToAssetPath(guid)),
        color = false,
        outline = false
    };
}
#

e.g.

dense crater
#

Oh that makes sense! Thank you!

hallow iris
remote lynx
#

how do you move them?

#

it doesnt move them in the script

hallow iris
#

rb = GetComponent<Rigidbody2D>();
enemy = GameObject.FindGameObjectWithTag("Enemy");

 Vector3 direction = enemy.transform.position - transform.position;
 rb.velocity = direction.normalized * force;

float rot = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rot + 90f);
this is on the FOV code

#

also cant join this to the fov for some reason

remote lynx
#

ohh

#

you move them in the other class?

hallow iris
#

i move them in the other script

remote lynx
#

is your bullet's rigidbody kinematic?

hallow iris
#

rigidbody 2d

summer stump
hallow iris
#

i am new to coding in unity so i dont get much i got this code from a tutorial

polar acorn
hallow iris
#

but it is not working

#

idk why

heavy kite
summer stump
summer stump
#

You need to access it though the other class. OR just not nest the class

remote lynx
heavy kite
remote lynx
polar acorn
summer stump
summer stump
remote lynx
#

it probably doesnt have to do anything with the kinematic

heavy kite
summer stump
polar acorn
summer stump
polar acorn
#

If you want to reference it you need to either move it out of there or use DialogueManager to access it

heavy kite
polar acorn
heavy kite
#

ok i understand now

remote lynx
#

@hallow iris why do you check the fov tho?

#

you set the velocity on start

#

btw you can simplify the FOV method into this```c#
private void FOV(){
Collider2D[] rangeCheck = Physics2D.OverlapCircleAll(transform.position, radius, targetLayer);
CanSeePlayer = false;
if (rangeCheck.Length > 0){
Transform target = rangeCheck[0].transform;
Vector2 directionToTarget = (target.position - transform.position).normalized;
if (Vector2.Angle(transform.right, directionToTarget) < angle / 2){
float distanceToTarget = Vector2.Distance(transform.position, target.position);

            if (!Physics2D.Raycast(transform.position, directionToTarget, distanceToTarget, obstructionLayer)){
                CanSeePlayer = true;
            }
            
        }
    }
}
hallow iris
remote lynx
#

you said that the bullet has this script attached?

remote lynx
#

it is attached to turret or the bullet?

hallow iris
remote lynx
#

oh thats weird

hexed terrace
#

The bullet should just have a script which moves it forward.
The turret should spawn the bullets facing the correct direction.

remote lynx
#

you should create different scripts

#

btw your turret has rigidbody?

hallow iris
#

yes

remote lynx
#

i gotta finish my project rn

#

can you do the thing Carwash said?

hallow iris
remote lynx
#

why?

hallow iris
#

this happend

#

my transform for spawn area also moved

remote lynx
hallow iris
remote lynx
#

it has rigidbody too right?

hallow iris
remote lynx
#

well you move the rigidbody of it in the turretScript

#

if you havent changed it

#

look at the Start method

hallow iris
#

it is ok when i freeze the x y and Z position

remote lynx
#

yes

#

because that way the rigidbody doesnt move

#

btw you have only 1 enemy in your world?

hallow iris
#

no multiple

#

there are slimes wolves and worms

#

i will add more

#

ngl i think i have botherd you too much

#

sorry for that

remote lynx
#

no problem

hallow iris
#

i think i am going to head off and reast my head for today

#

i have been working on the project for 12hours now

#

my thinking capacity has dimished

#

thanks for all of your help

remote lynx
#

thats a lot

hallow iris
#

i love it it is addicting

#

i tried making a random ememy spawn system

#

it works

remote lynx
#

nice

hallow iris
#

but it is a bit wonky

remote lynx
#

wdym by that

spiral path
#

can anyone help me im trying to make a 2d sprite move up and down but i cant who knows how

spiral path
#

opps

hexed terrace
#

!code

polar acorn
#

!code

eternal falconBOT
polar acorn
#

DOUBLE KILL

spiral path
#

!code

hallow iris
eternal falconBOT
spiral path
#

there you go

remote lynx
#

rb.velocity = Input.GetAxis("Vertical")

spiral path
spiral path
hexed terrace
#

Where did you get this code from?

spiral path
#

unity docs

remote lynx
#

moving = Input.GetAxis("Vertical") != 0;

#

it should work now

spiral path
#

ok

spiral path
remote lynx
#

edit -> project settings -> axes

#

there should be vertical there

#

if there isnt reset it from here

spiral path
#

ok

remote lynx
#

it may be case-sensitive btw

#

first letter is upper case

spiral path
#

ok it is

#

new code still not working i think im doing something wrong

remote lynx
#

add rigidbody2d from the inspector

#

and do only rb= GetComponent<Rigidbody2D>()

#

dont forget to set isKinematic to true in the inspector

remote lynx
spiral path
#

ok

remote lynx
#

u sure you are using the up and the down arrow keys?

#

and not w-s

#

to control it?

spiral path
#

ok

polar acorn
# spiral path ok it is

A Kinematic rigidbody does not respond to forces, so you cannot move it by setting the velocity

swift crag
#

I believe that works in 2D

keen dew
#

Input.GetAxis(Vertical) 🤔

swift crag
#

where is "Vertical" even coming from?

#

I see no such variable.

polar acorn
#

Just so I stop doing that

swift crag
remote lynx
summer stump
swift crag
#

if you're getting a compile error, say that

swift crag
#

I just tested it. Works fine.

#

this cube is on the move

#

look at him go!

#

i have no idea where those measurements came from

#

i'm interested in that now, actually..

#

it's showing me the size of the world-space bounding box for the selected object (if it has a renderer on it)

summer stump
#

Ah 2d. Yeah, I did see that way earlier

Honestly, that is one of the weirder differences between 2d and 3d imo

ruby python
#

Evenin' all. Would someone mind taking a look at the following code please?

I'm having a weird issue where my Shockwave gets spawned twice from my pool, but only one of the two that spawn 'trigger' the ShockwaveController script (Attached to the Shockwave), so it never 'despawns'. I'm a little confused as to what I'm doing wrong and why two Shockwaves are spawning on 'DoEnemyDeath();.

https://hastebin.com/share/juderoziwo.csharp

(I know the code is a little messy and I need to move the explosion stuff over to a pool.)

wintry quarry
ruby python
#

Ah my bad, one sec.

#
private void Update()
{
    if(enemyScript.enemyCurrentHealth <= 0)
    {
        DoEnemyDeath();
    }
}
    void DoEnemyDeath()
    {
        ExplosionSpawn(transform.position, 1f, "Death");

        // Add in Chance Check
        PowerUpDrop();
    }

    public void BulletImpact (Vector3 bulletPosition)
    {
        ExplosionSpawn(bulletPosition, 0.35f, "NotDeath");
    }
wintry quarry
#
private void Update()
{
    if(enemyScript.enemyCurrentHealth <= 0)
    {
        DoEnemyDeath();
    }
}```
Well this is going to run every frame, no?
#

It's pretty weird and inefficient to do such a check in Update

#

That's the kind of thing you should do at the moment the enemy takes damage

ruby python
rich adder
ruby python
stuck palm
#

@swift crag just realised, maybe its because some of my movement code is running in update could be ruining the determinism because of frame rate? updating the velocity vector is multiplied by deltaTime, though, so it should be fine? is there a difference between running it in update vs fixed update for deltatime?

swift crag
#

Yes. You can't do anything that depends on your framerate.

#

You need to do everything on a fixed cadence. You can still update visuals, play sounds, etc. in Update

mild onyx
#

i dont understand, his moves mine doesnt and he never says what buttons are causing the movement, i copied it exactly

#

this is to move a 2d sprite

stuck palm
swift crag
#

Yes.

stuck palm
#

i see, i'll change that immediately then

swift crag
#

imagine player 1 is running at 51 FPS and player 2 is running at 49 FPS

#

player 1 gets two frames before the next physics update

#

player 2 only gets one

stuck palm
# swift crag player 2 only gets one

i see. thanks! i think i didn't understand the purpose of deltatime, i thought it was something you'd use to get a similar effect to running it on fixed update

mild onyx
#

ignore my question, i made a spelling mistake

swift crag
#

And it does make your game's overall behavior framerate-independent

polar acorn
swift crag
#

But that doesn't mean that your framerate doesn't matter

#

If your game needs to be deterministic, then you must update it with a consistent timestep

summer stump
mild onyx
#

isnt rigid body just gravity?

swift crag
#

It's much more than that.

summer stump
# mild onyx why?

Transform movement is the same as teleporting, and rigidbodies are affected by forces, teleporting will mess up the physics.

No, it is not just gravity at all

swift crag
#

a Rigidbody tells the physics system that this object is going to move around and be affected by forces

#

If you just set the transform's position, the physics system will discover that the object has teleported (for no apparent reason)

mild onyx
#

transform and vector are the only 2 methods im aware of

summer stump
#

Neither of those are methods

mild onyx
#

both moved the sprite

summer stump
#

One is a class and the other is a struct

#

Translate is a method though

#

You would USE a vector in rigidbody movement too

#

Look into MovePosition, AddForce, and .velocity

mild onyx
#

you know what i meant, i wasnt using coding speach when i said method

summer stump
#

I truly did not know what you meant.

mild onyx
summer stump
#

That way none of them will do that

#

Translate will cause that too if you bump into something and the physics engine actually manages to catch the collision despite teleporting

mild onyx
summer stump
#

In a physics simulation, round objects will certainly roll, so yes you are right about the cause

mild onyx
#

thanks

dense root
#

Do these two lines accomplish the same thing?

        if (other.gameObject.layer == LayerMask.NameToLayer("Player"))
        {
            hasEntered = true;
        }
        if (collision.gameObject.layer == LayerMask.NameToLayer("Player"))
        {
            hasEntered = true;
        }
summer stump
#

If you didn't change the parameter name, then one of the two will be a compile error
But yeah, the compiler doesn't care what name you call it as long as it matches the declaration (and it is not a reserved keyword that isn't handled properly)

dense root
#

Oh okay, yeah I am using both in the same script

summer stump
dense root
#

Oh, so yeah they do the same thing

#

I just need to be more consistent with my naming

summer stump
#

Yeah. What you're doing is completely fine in terms of the compiler. Consistency would be nice, but it's whatever for something like this hahah

#

Then name collision is usually used for the OnCollisionEnter method which passes a struct called Collision2D though. But yeah, it's local, it won't affect anything else

dense root
#

Awesome, thank you so much

sharp abyss
#

Anybody know how can I make a stake gun like in painkiller that pins enemies to the wall?

rich adder
#

then add some simple joints, set the anchor pos to be the raycast point

dense root
#

What's causing my spite image to swap out on start? The only script attached to it doesn't swap out sprites, what could be the cause?
https://gdl.space/muyuyolezo.cs

long jacinth
#
            other.gameObject.GetComponent<SpriteRenderer>().sprite =  playerWeapon.sprite;```
#

how can i do this?

#

like switch the properties of the two variable

mild onyx
#

i copied my jump code and edited for my positive horizontal movement and got this: if (Input.GetKeyDown(KeyCode.RightArrow) == true)
{
myRigidbody.velocity = Vector2.right * 10;
}

#

it doesnt work and just cancels my jump

polar acorn
bleak glacier
#

Any reason why this coroutine wouldn't be stopping? ```void Update()
{
Vector2 inputVector = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
rb.velocity = inputVector * speed;

  if (Input.GetKeyDown("left shift"))
  {
    speed = speed + 1;
    StartCoroutine(subtractEnergy());
  }
  
  if (Input.GetKeyUp("left shift"))
  {
    speed = speed - 1;
    StopCoroutine(subtractEnergy());
  }
}
          IEnumerator subtractEnergy()
    {
        for(;;)
        {
        energy = energy - 1;
        yield return new WaitForSeconds(1f);
        }
    
    } ```
polar acorn
dense root
mild onyx
outer solar
#

Im following a tutorial to make a car but my wheels just rotate by 90° when i start the game.
can anyone help me fix that?

thats the part of the code for the Wheels:
private void UpdateSingleWheel(WheelCollider wheelCollider, Transform wheelTransform)
{
Vector3 pos;
Quaternion rot;
wheelCollider.GetWorldPose(out pos, out rot);
wheelTransform.rotation = rot;
wheelTransform.position = pos;
}

rich adder
#

share the full script we might be able to help out more. Wouldn't hurt to share video as wel

outer solar
rich adder
#

then you linked your objects wrong

#

have probably incorrect pivot

#

how else we supposed to know whats wrong with that snippet alone

outer solar
rich adder
#

in pivot / local mode

outer solar
raw token
rich adder
# outer solar

show the gizmos for each wheel, show the entire scene view so I can seee if~~ gizmos are on Local~~ ok its local since the X pointing down

#

also you have still Center mode on though

outer solar
#

the wheels are all rotatet like they should as far as i know

mild onyx
#

oh yeah, any ideas on how to click between two letters of code? currently i cant add a letter without having to rewrite everything after

swift crag
#

It looks like the wheels are starting with a 90 degree Y-axis rotation

neon ivy
#

I'm trying to set a bool to true when a microphone is hearing something. but there's no such feature in the Microphone class. anyone know how to do this?

swift crag
#

Now show the wheel collider's inspector

#

It looks like you have a 90 degree offset between the two

outer solar
swift crag
#

yep

#

Notice how the blue arrow points in different directions

#

When you copy the world-space rotation of the collider onto the wheel, the blue arrows are aligned

outer solar
#

the colliders dont rotate just the model

swift crag
#

There are two options here

swift crag
# outer solar the colliders dont rotate just the model
private void UpdateSingleWheel(WheelCollider wheelCollider, Transform wheelTransform)
{
    Vector3 pos;
    Quaternion rot;
    wheelCollider.GetWorldPose(out pos, out rot);
    wheelTransform.rotation = rot;
    wheelTransform.position = pos;
}

You can combine the rotation you get from GetWorldPose with the original rotation of the wheel

#

So, you'd do something like this:

#
wheelTransform.localRotation = Quaternion.AngleAxis(-90, Vector3.up);
wheelTransform.rotation *= rot;

This will set the wheels' rotation back to how it started, then apply the wheel collider's rotation on top of that

#

The second option would be to just parent each wheel to an empty object.

#

Set the rotation of the empty object.

#
  • Car
    • Empty <-- rotation of [0,0,0]
      • Wheel Model <-- rotation of [0,-90,0]
#

This is an easy way to deal with a model that needs an odd position, rotation, or scale

#

You get it lined up properly beneath the empty object. Now you can just move that empty around however you want.

outer solar
#

Thanks a lot!

swift crag
#

np!

swift crag
#

but otherwise, it's easier to just line your models up properly

onyx tide
#

Hello i'm new on unity. It is good to use the package "Input System" for the main character ? I don't found a lot of tutorial with this

wintry quarry
magic panther
#

I'm curious. Why does an arrow work for the player here but not an equals sign like above for the moveDir?

wintry quarry
swift crag
#

you can't initialize a field with another field or property

#

actually, what is this?

#

it's kind of a member, but not really

#

either way, you are not allowed to look at yourself in field initializers

#
public int x = y;
public int y = x;
#

imagine the pandemonium

magic panther
#

I think I get it

swift crag
#
private Player player = null;
#

This would be fine.

wintry quarry
magic panther
#

so can I jsut write this instead of creating a player and using it?

wintry quarry
#

Yes there's no reason for that property to exist, you can just use this

swift crag
#

"instead of creating a Player"

#

this is part of the Player class!

magic panther
#

this.transform.position += new Vector3(moveDir.x, moveDir.y, 0f); should work if I understand you guys correctly

polar acorn
wintry quarry
swift crag
#

It's implicitly added when you use a name that isn't a local variable.

#
int x = 123;
this.x = x;
#

it is mandatory when that's the case

#

this creates a local variable called x that contains the value 123, then writes it into a field called x

#
public class Foo {
  public int x;

  public void Something() {
    int x = 123;
    this.x = x;
  }
}
#

e.g.

ionic zephyr
#

does anyone know how to put an item into the crafting slot by cliking on it like in this example?

rich adder
ionic zephyr
bold plover
#

So I don't mess up my files while reorganizing, do I change the file name in my Unity program or in my IDE instead? Or both simulatenously? I'm worried if I do one over another or out of order it will break my references.

rich adder
ionic zephyr
#

think of Minecraft for example

fringe kite
bold plover
# fringe kite

Is it possible the raycast you are using is not checking for the parent object while being inside the center?

ionic zephyr
fringe kite
bold plover
#

That's strange. What are you trying to use the raycast for specifically? That will help better figure out the issue.

#

If the feet are making contact with the ground then even with a distance of zero it's possible it's still returning true because of direct contact.

rich adder
fringe kite
ionic zephyr
fringe kite
#

mystics

raw token
bold plover
#

Ok cool. I'll do a backup anyway but just wanted to double check.

bold plover
bold plover
queen adder
#

new to unity, following tutorial, not working, what is wrong with my declaration (3D rigidbody)?

Rigidbody rb; rb = GetComponent<RigidBody>();

queen adder
slender nymph
#

spell it right

polar acorn
frosty hound
bold plover
#

Syntax strikes again.

#

it do be like that

fringe kite
queen adder
swift crag
bold plover
#

Yeah it's probably just the capitalization of the "b".

polar acorn
frosty hound
polar acorn
swift crag
#

🤓 actually

swift crag
#

this is not a syntax error

stuck palm
#

@swift crag strangely enough sometimes replays work absolutely frame perfectly (overlaid a recording of the original and the replay and there was no weird overlap) and sometimes they dont work as well. i've only been able to record 1 player moving at a time so far

polar acorn
swift crag
#

the syntax of C# is its grammar; a bogus name is not a syntax error

#

it does fail to compile when the compiler tries to figure out what that name means, though

queen adder
bold plover
#

<Rigidbody2D>

polar acorn
bold plover
#

I don't think it matters. The issue was spotted.

#

So is it working now BIG?

queen adder
#

no hahaha

swift crag
#

well, it is good to recognize the error that was made...

#

instead of just asserting that the tutorial was wrong

polar acorn
# queen adder in the tutorial he spells it wrong, so whoops haha
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 166
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2024-06-25
queen adder
#

😂

bold plover
#

Didn't say it wasn't but no point getting hung up on that. It happens.

queen adder
#

bros keeping score, and I added to it angerjoy

swift crag
bold plover
#

Sometimes you just need a second set of eyes.

polar acorn
queen adder
#

or maybe I just need to get gud

rich adder
#

or glasses

queen adder
#

I actually need glasses badly

#

being poor is sucks

#

so this should work then?

Rigidbody3D rb; rb = GetComponent<Rigidbody3D>();

polar acorn
queen adder
rich adder
#

this isn't a puzzle game

polar acorn
#

Why make up a class instead of using the one whose documentation you were sent

raw token
#

If your IDE is properly configured, it should be suggesting possible values, and highlighting things that are wrong

bold plover
#

True. Trust it helps.

queen adder
bold plover
#

When I started I didn't know you could configure and was just tabbing in and out of Unity.

willow scroll
frosty hound
#

The documentation is the 3D one

bold plover
#

Behold there was an easier way.

polar acorn
#

That's the name

#

You can look at the name and see the name of the thing

#

🤯

bold plover
#

So just <Rigidbody>.

queen adder
eternal falconBOT
#

:teacher: Unity Learn ↗

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

queen adder
#

that's why I came here to ask, sorry if I haven't nailed down the naming conventions yet guys

bold plover
#

<Rigidbody3D> isn't needed.

willow scroll
spare mountain
bold plover
willow scroll
queen adder
#

I created the exact project I am working on in Godot, I just switched to unity. I don't need to go throguh all those tutorials I just need a few pointers

willow scroll
spare mountain
# bold plover In a beginner chat?

this is not a "we will walk you through the basics of coding" this is a "you know how to code basic things but have a beginner question" channel

bold plover
#

I mean in the time it took you to link a bunch I just answered the question.

queen adder
bold plover
#

In a single line.

summer stump
summer stump
bold plover
#

Catching a mispelling isn't spoonfeeding.

#

lol

spare mountain
bold plover
#

You

#

Are the ones still @ing me about it.

#

but ok

swift crag
summer stump
bold plover
#

I don't think saying "oh you mispelled something" is hand-holding.

swift crag
#

you want to encourage people to learn to solve problems

swift crag
queen adder
#

the article linked did not specify it was specifically for 3D. I saw that article before I answered the question. Because I am not familiar with the Unity naming conventions, I assumed thaat since the tutorial was using Rigidbody2D, the 3D one would naturally (apparently not) be Rigidbody3D.

rich adder
#

it tells you everything the class can do

summer stump
bold plover
willow scroll
queen adder
#

I wasn't even sure the 3D part was correct.

#

which it wasnt

rich adder
#

what they learn if you do "do this , copy that"

swift crag
#

If you don't understand something about a resource, you should ask about it

#

"Is this the 3D rigidbody?"

#

whilst showing initiative is good in a sense, randomly guessing names isn't very useful

bold plover
#

It was a capitalization of the "b". It's not that deep.

swift crag
summer stump
bold plover
neon ivy
#

I copied this function from a youtube tutorial and tested it out but I'm getting an error message I do not understand...
code:

private void Update()
{
    if(GetLoudnessFromAudioClip(Microphone.GetPosition(device),micOutput) * 100 > micThreshold)
    {
        Debug.Log("Heard");
    }
}


private float GetLoudnessFromAudioClip(int clipPosition, AudioClip clip)
{
    int startPosition = clipPosition - sampleWindow;
    float[] waveData = new float[sampleWindow];
    clip.GetData(waveData, startPosition);
    float loudness = 0;
    for(int i = 0; i < sampleWindow ; i++)
    {
        loudness += Mathf.Abs(waveData[i]);
    }
    return loudness / sampleWindow;
}
``` error:
```C:\build\output\unity\unity\Modules\Audio\Public\sound\SoundManager.cpp(811) : Error executing result = instance->m_Sound->lock(offsetBytes, lengthBytes, &ptr1, &ptr2, &len1, &len2) (An invalid parameter was passed to this function. )
UnityEngine.AudioClip:GetData (single[],int)```
short hazel
#

The subtraction you're doing a few lines above could yield a negative number for example

neon ivy
#

oh...

#

yep that's it :I idk how the video didn't have that issue.

#

UnityChanThumbsUp thanks

stuck palm
#

are rigidbodies deterministic?

summer stump
swift crag
#

shebb is embarking on the wild ride of a multiplayer fighting game

ionic zephyr
#

if I want to show in the slots of my crafting station the items I am placing is it better to instantiate an image in the slot transform?

wintry quarry
#

Would probably have Image components there already and just set the sprites as needed

stoic spear
#

i am once again going insane, there must be a good way to do this

swift crag
#

can't really do a for loop there

#

I guess you could if they're consecutive enum values

stoic spear
#

Input.inputString maybe?

wintry quarry
#
KeyCode[] hotbarKeys = new KeyCode[] { KeyCode.Alpha1, KeyCode.Alpha2, ... etc };

void Update() {
   for (int i = 0; i < hobarKeys.Length; i++) {
     if (Input.GetKeyDown(hotbarKeys[i]) && heldFirearms[i] != null) {
       ChangeFirearm(i);
     }
   }
}```
#

@stoic spear

stoic spear
#

clip it to only numerical values

stoic spear
#

oh, nice

swift crag
#

I was going to suggest something awful

#
for (int why = (int) KeyCode.Alpha1; why < (int) KeyCode.Alpha9; ++why)
wintry quarry
#

That's also an option

#

and probably works

swift crag
#

praetor's is much easier to grok

wintry quarry
#

But this is more configurable and yeah easier to explain

swift crag
#

also mine is wrong because it skips key code 9

naive pawn
#

just <=

old rivet
rotund forum
#

Hopefully this is a simple question to answer, but I was thinking about how I would handle damage done to enemy characters in my game.

The player can shoot bullet projectiles, and I was thinking of just giving separate colliders to the upper arms, lower arms, and etc. (specifically just for taking damage) of the enemy units so that one could aim and essentially shoot at the mesh of the enemy (as opposed to the capsule collider I have on them now so they don't fall through the ground).

Is this a solid way to do this or am I overcomplicating things?

west sonnet
#

how can I change the size of a collider in script? I'm trying to do collider.size but it's not recognizing the .size

swift crag
#

I would create a Hurtbox component (or Hitbox -- "hurtbox" is more common in a fighting game where "hitbox" is used to attack)

summer stump
swift crag
#

It would specify how much it hurts to get hit in that spot

swift crag
swift crag
#

because it's not specific enough

#

you need to know what kind of collider you have

west sonnet
#

Thank you!

swift crag
#

something like that

summer stump
west sonnet
rotund forum
#

Just very doubtful of myself sometimes!

#

🙏

stuck palm
magic panther
#

apparently I'm doing something wrong

#

cinemachine is installed

wintry quarry
#

The namespace of all the classes is listed on the left and on each page fpor each class.

#

hint: it's not Cinemachine

magic panther
#

the guy is using Cinemachine. Is this just outdated?

#

1 year old vid

wintry quarry
#

Your IDE should suggest the correct namespace for you

magic panther
#

it's not

wintry quarry
#

You may need to do "regenerate project files"

#

from the external tools menu

#

And yeah it depends which version of cinemachine you have

#

In 2.xx versions it's Cinemachine

#

In 3.xx it's Unity.Cinemachine

magic panther
#

also not that

#

where's the external tools?

wintry quarry
#

in preferences

#

(this is from my mac, windows may look slightly different)

magic panther
#

seems to work so far

#

it's no longer underlined

lusty nest
#

I have a prefab of a ragdoll and after the ragdoll has has been moved around, I would like to have a function that would be able to "restore" the ragdoll to the state it was in the prefab. Is there any simple way to do this ?

eternal needle
stuck palm
#

@swift crag I've come to the conclusion that framerate is still an issue for keeping my game deterministic, as well as dynamic rigidbody projectiles. for some reason, recording games using the recorder makes the framerate really low, but it also somehow has the added quirk of keeping the games without rigidbody projectile characters very in sync

#

lots to sort out clearly

misty pecan
#

private void Spawn(int level, int amount, float delay)
{
float spawnTimer = 0;

for (int enemiesSpawned = 0; enemiesSpawned < amount; enemiesSpawned++)
{
    while (spawnTimer < delay)
    {
        spawnTimer += Time.deltaTime;
    }

    Instantiate(enemyArray[level - 1], transform.position, transform.rotation);
}

}

why is this just spawning them all instantly???

swift crag
#

this shows the exact problem you're having

wintry quarry
#

Age is just a number, and so is deltaTime. Using deltaTime doesn't magically cause time to elapse in game.

ionic zephyr
#

what can i do to make sure that whenever I stop using a crafting station but I haven´t crafted anything that my objects don´t get lost?

wintry quarry
swift crag
#

one option would be to have a method that runs as you close the crafting menu

#

it would attempt to move every item still in a crafting slot into the inventory of whoever was using it

#

and, failing that, turn them into drops that drop on the ground

wintry quarry
#

I mean realistically I would just leave the player's inventory alone entirely until they actually craft something.

#

I don't see why anything should change before actually crafting

spiral raven
swift crag
#

this is something like Mincraft's crafting table

#

which could make it more difficult to "reserve" items like that

stoic spear
wintry quarry
stoic spear
#

if i > heldFirearms.Count-1 ?

wintry quarry
#

would just update the for condition like this honestly

ionic zephyr
#

I dont know how to create that staging area

wintry quarry
#

if you want to like... let the player know with a sound or something

#

the world is your oyster

stoic spear
#

thats working great, thanks!

misty pecan
#

private void Spawn(int level, int amount, float delay)
{
for (int enemiesSpawned = 0; enemiesSpawned < amount; enemiesSpawned++)
{
StartCoroutine(WaitThenSpawn(level, delay));
}
}

IEnumerator WaitThenSpawn(int level, float delay)
{
    yield return new WaitForSeconds(delay);
    Instantiate(enemyArray[level - 1], transform.position, transform.rotation);
}

Why is this spawning them all at once?? It waits for the delay and then spawns the full amount at once, Why?

swift crag
#

StartCoroutine does not "delay" the method that called it

#

That would freeze your game.

#

You're starting many coroutines. They all wait for a delay, then spawn an enemy.

#

The page I linked you to shows you exactly how to perform the same action many times with a delay

#
IEnumerator Fade()
{
    Color c = renderer.material.color;
    for (float alpha = 1f; alpha >= 0; alpha -= 0.1f)
    {
        c.a = alpha;
        renderer.material.color = c;
        yield return new WaitForSeconds(.1f);
    }
}
misty pecan
#

It gives an error

swift crag
#

and what is the error?

misty pecan
#

Error (active) CS1624 The body of 'LevelManager.Spawn(int, int, float)' cannot be an iterator block because 'void' is not an iterator

#

Because voids dont return a value yes?

swift crag
#

You're trying to use yield return new WaitForSeconds(...) in your Spawn method

#

it's not a "void". It's a method whose return type is void

swift crag
#

(as you've already done)

misty pecan
#

ah

#

i think i get it now

#

just no coroutine this time?

swift crag
#

No. You need a coroutine.

swift crag
#

You have to pass the returned object to StartCoroutine.

swift crag
#

all you have to do is put the for loop in the IEnumerator method

misty pecan
#

will do

uneven mulch
#

Does anyone know the solution to this problem?
In the editor and all the UI works, but it doesn't in the build. Unity 2D

swift crag
#

what does "works" mean?

#

are you unable to click on anything?

uneven mulch
#

You can see it in the editor

#

But not in the build

swift crag
#

Try changing the resolution of the Game View

#

see if your UI moves around or disappears

uneven mulch
#

Mhm

uneven mulch
swift crag
#

"Doesn't work?"

#

this isn't a "fix"

uneven mulch
#

You can't see it

swift crag
#

I'm asking you to change the resolution of the Game View and seeing what happens to the UI

#

This has no effect on the built game

uneven mulch
#

Oh

#

It does now

#

In the 4k view you can see it

#

In normal hd you cant

swift crag
#

You need to fix your anchors.

#

You can read about how RectTransforms work here

#

the general idea is that, if something goes in the top left corner, it needs to be anchored to that corner

#

By default, everything is anchored to the center

#

This means that as the resolution changes, the position will change

#

if something is always 1000 pixels to the left of center, then it will fly off-screen at low resolutions

uneven mulch
#

yep

#

i fix it

#

now

low hatch
#

i need help, I can't add any references to this one script, not sure what i have done wrong

#

I cant drag anything into it either

polar acorn
# low hatch

Do you have anything with a Button component on it?

low hatch
#

wdym

polar acorn
#

You're trying to reference a Button. What Button

summer stump
# low hatch wdym

See #854851968446365696
It explicitly lists wdym as something you should not respond with.

Do you not know what button is? Or was "on it" unclear? They mean attached to a gameobject.
We don't know what you know, so wdym is an unhelpful response

low hatch
#

ah ok

#

thanks for letting me know that

#

i should also be able to figure out the component reference

vast vessel
#

whats the issue here?

swift crag
#

look at the signature of EnumPopup

#

it returns Enum

#

That's less specific than your exact enum type

#

You have to explicitly cast it back to the enum type you want

stuck palm
#

GameManager.Instance.RNG = new Random((uint)replay.randomSeed);

when i create an RNG, does it immediately change the seed after i do this?

long jacinth
#

playerWeapon.sprite = other.gameObject.GetComponent<SpriteRenderer>().sprite;
other.gameObject.GetComponent<SpriteRenderer>().sprite = playerWeapon.sprite;

#

How do i do this but with it actually working

swift crag
swift crag
#

"actually working"?

#

is there a compile error?

#

It looks like you want to swap the two sprites

long jacinth
long jacinth
swift crag
#

Put the first sprite in a variable.

#

that way you can access it after you overwrite the player's weapon sprite

stuck palm
long jacinth
#

wait a second

#

nah its good

#

wait no this is weird

#

one second im gonna take time to think through this

remote osprey
#

hello

#

Can a child property have a way to know the identity of the scriptable object its a child of?

cosmic dagger
remote osprey
#

I just needed a method that returns the parent from the child

stuck palm
remote osprey
#

I have a CardSO that houses an EventSO, I need to know the CardSO from EventSO

cosmic dagger
remote osprey
#

Yeah, tbh I think I'm confused

#

I was making the same mistake again of forgetting i had passed my CardSO data to my CardData

cosmic dagger
#

Oh, okay. The parent/child is for a GameObject. You'd have to pass a reference to the EventSO . . .

remote osprey
#

Problem is i can't alter it runtime

#

Ok, so i'm in a pickle

#

I want to make a complex event system that goes as follows:

  • Invoker deals x damage to Enemy Player
  • Invoker deals x damage to Enemy Summon
  • Invoker deals x damage to Enemies (Player and summons)
  • Invoker deals x damage to Enemy Summons
  • Invoker deals x damage to Random Enemy
  • Invoker deals x damage to Summon
  • Invoker deals x damage to Random Player
  • etc...
#

But i don't want it to just be "deal x damage" it could also be apply "rot debuff"

remote osprey
#

And since its an SO, i can't modify iit runtime

#

I shouldn't be able to modify events anyway, since they represent commands.

#

So I need a way to know at runtime

  1. who the target to the event is (if there is a need for a target)
  2. what kind of target it is
#

I believe 2) would be achievable with a TargetGenerator abstract class

#
  1. is what I can't get around, because I don't know to which card the event belongs to
summer stump
remote osprey
mild onyx
#

is there a way i could merge these two sections of code? movement direction requires both x and y however i dont want the w and s keys to do anything, just the space bar to do a simple jump

rich adder
#

you only passed 1

#

the name, vector2 🙂

mild onyx
#

so if i put vector 1 it will be fine?

rich adder
#

vector1 is just a float

polar acorn
rich adder
#

good thing they renamed all the vector1s into floats lol

strong wren
#

how do i fix this error?

#
    {
        if (collision.gameObject.CompareTag("EnemySlap"))
        {
            S.Health -= 1;
        }
    }```
rich adder
strong wren
#

this is the code related to the error

polar acorn
rich adder
stuck palm
rich adder
#

we can't read lines number from one snippet alone

strong wren
rich adder
#

lol

#

big brain reply

strong wren
#

which would be S.Health -= 1

strong wren
#

i know im smart

rich adder
#

make it not be null

polar acorn
raw token
polar acorn
strong wren
#

alright

#

i didnt select the gameobject with the sciript S

#

ye i found it

#

thanks yall

#

idk how yall put with me

#

i hate myself so it wouldnt be something rare for yall to hate me too

rich adder
#

lol just post code properly next time

mild onyx
strong wren
rich adder
#

if you're gonna show us the line number send the whole script or just tells us which one is line 51

strong wren
rich adder