#💻┃code-beginner
1 messages · Page 397 of 1
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
Are you referring to not having any extra motion simulated relative to your velocity you've added?
this is my first time with c# and i know NOTHING
Yes typically scripts do a "grounded check" to make sure you're on the ground when you try to jump
You should find and follow a basic tutorial.
any basic tutorial will cover this
the tutorial i was following was for flappybird
ok well flappy bird jumps in the air so
what did you expect
find a different one
You'll need to find a tutorial for single/multi jump etc (plenty of unity tutorials on the internet that would better cover this than discussing it on Discord)
can you not serialise vector3's?
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
You're trying to serialize the normalized property
how did you install newtonsoft JSON
Making a game is pretty hard unless you're making something simple or are lucky to find reference material similar to what you're wanting to make.
via the package manager
i shouldnt be
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
You have to be carefuil with newtonsoft
it tries to serialize properties by default
Tbh, you probably can as long as you know what you're doing and are able to integrate the resources together.
No one really cares about theft of code (especially from a tutorial), cheating (modifying json files) etc
Assets are a no go though.
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
Does Json.net have any way to specify only the properties you want to be serialized? or alternatively serialize certain properties based on binding flags like Declared Only?
Right now I am using J...
so rather than serializing Vector3 - I would make my own serializable Vector3 with the appropriate annotations. And perhaps an implicit conversion operator between them
However... afaik this is supposed to be included?
https://github.com/applejag/Newtonsoft.Json-for-Unity.Converters
so I'm a little confused why it's not working
thats annoying lol, how can you program a conversion operator?
I mean actually this specific case is referenced here https://github.com/applejag/Newtonsoft.Json-for-Unity.Converters?tab=readme-ov-file#what-does-it-solve
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
how do i add it? via git on the package manager?
installation instructions are in the link
oh i see soz, thanks will try this
This one seems visually similar to yours https://youtu.be/P_6W-36QfLA?si=Kvfx-AsRl7vXJUcc
(Random Youtube video)
just to clarify im using this package
I know
the converters package is separate
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.
ill have to check it out tommorow but thanks, tried to add some horizontal movement and my character rolls instead of sliding😂 , ill have to see what i can do tomorrow
Yes it would probably tank performance. Consider using an asset such as: https://assetstore.unity.com/packages/tools/physics/obi-fluid-63067
Or consider using compute shaders or ECS.
Constrain rotation etc from the inspector
just installed the converters package. do i need to do anything else for it to work?
Worth reading this section: https://github.com/applejag/Newtonsoft.Json-for-Unity.Converters?tab=readme-ov-file#configuring-converters
hmm, i guess i can simplify it,
so i can still make a lot of small square bodies, but after the .eventDestruction
i would go in a loop
and descend any body that has no body below it
so that i do not get the floating in the air sand
oh wait, i can just give them gravity speed, no need to loop over 
ah okay, thansk
this should make it easier on the cpu, since the only processing would be when it is going down - which is simple gravity
im getting this error, now. no idea what the particle system is doing in there
[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?
JsonIgnore should work fine...
Make sure you're using Newtonsoft.Json.JsonIgnore and not System.Text.Json.Serialization.JsonIgnore
In the animator I made a transition from Entry to Walk but there are no parameters. Can anyone please help?
don't cross post plz
The entry state can't have parameters. That's the state you start in
how do I add an overhead ui to an object when i have my mouse over the object
Which part do you specifically struggle with?
Have a world space canvas that you move around and activate when needed.
uh tryna add a canvas to my object
whats a world space cnvas
A canvas set to render in world space.
Check the canvas page in the manual to learn how it works
can u send me the link to it
Your canvas shouldnt be on your objects, your objects should be children of some canvas in the scene
Don't expect people to google for you.
It's really easy too. Just type: "unity canvas manual" in google and hit enter.
oh i thought it was somewhere in unity
It is. In unity manual. And you google to find the link.
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?
You need to provide something actionable
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!
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
also i am looking at it now and it sometimes works and sometimes gets stuck?
but just one the one side where dropper is on left side
Show the inspector for the ore. Specifically the rigidbody settings
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?
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
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
i tried that and im pretty sure it just fixed
why does that just fix it, i dont understand
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));
}
}
https://www.youtube.com/watch?v=eXsSsexoVGc&list=PL0GUZtUkX6t4JrdjOoAF2ayH-ksVtgpqy
tutorial I'm working from
Patreon: https://www.patreon.com/user?u=28674164
Ko-fi: https://ko-fi.com/gregdevstuff
Twitter: https://twitter.com/GregDevStuff1
Discord: https://discord.com/invite/6Hav9Hc
Join this channel to get access to perks:
https://www.youtube.com/channel/UCZAenDNR0vQRqQAHiQ6JXgg/join
Boxes catch on the edges of other boxes.
The positioning is never going to be EXACTLY perfect no matter what, so tiny lips may be catching. The rounded edges just force the collider up over that lip
ok that makes sense thank you so much for the help
you have an extra semicolon on a method, usually you should look at the topmost error
not the bottom
i only really noticed because i pasted it and saw the top most error as well
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
this also indicates your !IDE isnt configured, or you wouldve noticed some errors way earlier
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
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?
how large is the data ? also Replace returns a string
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
this is a unity server. try asking in the !cs server
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
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
i'd recommend doing some more research on the topic of factory games to see how they typically set up the conveyors. they don't typically use physical objects, especially not individual rigidbodies for the items on conveyors because if you have more than just a few dozen it starts to really lag
ok thats fine
how do i make higher gravity in the unity scene, like things look floaty
i'd bet the issue is you overwriting gravity rather than "too low" gravity
well when the ore drops from dropper it looks so floaty falling down to ground
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
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?
raycasting is fairly cheap
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)?
profile it and find out
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!
In general you can do several thousand raycasts per frame without any noticeable difference in performance
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?
Ah, that's a really handy baseline to know, thank you!
to add on to this, i benchmarked raycasting to see how demanding it is and i was able to do over 1000 raycasts in a very short amount of time. granted it was in an empty scene #💻┃code-beginner message
profile when you notice performance issues or when you need to find out what is impacting performance the most 🤷♂️
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
are you sure you aren't doing something silly like multiplying mouse input by deltaTime
lemme check
I'm using Time.unscaledDeltaTime as a multiplier which is in the Update() loop
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
Added a bunch of physics cubes to add lag and the camera movement has no visible jitter. That was probably it. Thanks!
how do i fix?
when i click play it works, then when i click to place something the game just pauses
probably infinite loop bro
does the editor pause too?
or only game?
then you probably changed Time.timeScale to 0
but i havent
am i blind i cant see time scale
btw it like literatly pauses my game.
like the pause button at the top is blue
can you send your code that places things?
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
maybe it is inf loop
i changed 5 lines of code and basically swapped positions on 2 objects
an infinite loop would cause the entire editor to freeze
then stop ignoring the errors in your console
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
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
its annoying because it was working and now suddenly not
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
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
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...
basically trying to recreate this but in unity and with movement 🙂
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
Check input rebinding samples. I believe you are supposed to change inputs with overrides. Removing all overrides would essentially be reverting to the "default". #🖱️┃input-system
Why my editor thingys are invisible , they were working just fine before
Not a code issue. Try either resetting your layout (not sure if this will work) or restart the editor
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 parts
and i feel that having like 4000 rigid bodies is kind of too much
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
Is "Loop Time" checked on the animations?
there's the problem, yep
click on the model the animations came from, go to the Animation tab, and check "Loop Time" on each animation
@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.
That would work, but it would prevent you from re-using the replay logic for multiplayer
because some bs keeps happening and like a single event i cant determine will throw the whole thing out of whack
how come?
you want to be able to accurately re-create the same game state on both sides by just sending inputs back and forth
i see.
Sending positions and velocities over would mean that one player's game is controlling the other player's game
or...something like that
One thing you could do is add more of these "hash checks"
i've been able to do it somewhat consistently, but some replays will just go completely out of whack after like one thing and i dont understand why 😭 no errors or anything
it won't be an error
i know
it'll be something you did that is non-deterministic
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.
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
what about that seed thing you recommended?
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
hm okay
You can create a System.Random and store it in a static field
or use Unity.Mathematics.Random, which is a little closer to the UnityEngine.Random that you're used to
unity.random and unity.maths.random are not linked in any way im guessing?
is there anyway to get like a callback or something whenever random is used?
No.
zamn
You create an instance of Unity.Mathematics.Random. It's not static
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
By the way, if you're up to try to do rollback, you will need a way to serialize and deserialize your current game state (and QUICKLY!)
Arent the random values always the same depending on the seed?
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?
The problem is that everyone uses the same global RNG state with UnityEngine.Random, so other code can interfere with your RNG state
the only time i use Random in my character script is for shaking the mesh when you get hit, and playing different sounds.
It's a hack that can blow up in your face if done incorrectly!
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
If it's purely cosmetic stuff, then that should be fine
As long as you do not save and restore the SO state, it will always RESET on runtime. Do not expect the editor behaviour on runtime
Aaah okay, I get you. Was just thinking simple data, mainly level name/value that gets chosen in the main menu when starting up a game.
Just stick it in a static field or on a DontDestroyOnLoad'd object
The general idea is that:
- Every frame, you serialize the game state
- When you need to roll back, you deserialize an old state, then replay inputs
still worth a try i guess, maybe the matchmanager would create an instance or something that gets passed to the characters?
This is one hell of a "general idea" here
Both sides should be given the same seed on game start
yeah. annoyingly mathematics.random doesnt have insideunitcircle
Okeydoke. 🙂 Thanks. Learning SO's atm so figured it was worth an ask 🙂
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
@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?
and this is how the tile started
character class is a SO and all Character SOs have stats
so i dont understand why
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
is it because my code updates it without any delays? is this the case why tiles are not behaving like specified in code?
problem was that a prefab that needs Character class SO didnt have one
thanks for the help
Do you mean you have Domain Reload turned off?
I don’t turn it off or on
The only thing I did was switch the target to iOS and I think that is all o changed in project settings
Everything else is the default 2d project you get from unity
then I don't get what you mean by 'my code updates it without any delays'
Like
Maybe it is so fast that some updates are ignored?
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
Then you need to Debug your script
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?
If you've queried the RNG for a value, the state will change.
is it okay if I reuse the script of my inventory slots to create crafting slots or might it be really confusing?
Depending on your slots implementation, it might be completely reasonable to do so
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
however, the crafting items can only hold a quantity of 1 item per slot
think of Minecraft for example
those types of slots should be different scripts/classes?
Then introduce a variable for a max stack size in your slot script if you haven't done it already
okay, thanks a lot!
Not really, a slot is a slot - it holds a certain amount of an item. It doesn't necessarily need to know what owns the slot and how it's used, that's the job of another script which simply uses the slot for it's own purposes
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.
I'm confused, has the original seed not been used?
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
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
Come to think of it in the same frame there are other queries so that probably changes the state. I've tested multiple times and it always ends up at that numby
That's expected, then
Each time you query the RNG, its state updates.
Ah I didn't know that, I thought the state stayed the same
I'm assuming if it stays the same then I'll just get the same number every time
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!
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
can I ask a quick question about github here or should I join a dedicated github discord? it is somewhat related to unity
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
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
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?
Check AssetDatabase.FindAssets.
have you put your scene in the build ?
I should ask why you're trying to do this, though
I’m writing something that will only run in the editor
there is no channel for asking about unity and google play billing 6 right?
I’ll try this out, I tried it a bit ago but only could get garbage out for some reason. Hopefully I was just doing something wrong lol
this is about Google Play billing, not about a specific unity payment service
It gives you GUIDs. You have to load the individual assets.
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.
Oh that makes sense! Thank you!
whats wrong with the bullets?
they do not move
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
i move them in the other script
is your bullet's rigidbody kinematic?
rigidbody 2d
But is it kinematic?
i am new to coding in unity so i dont get much i got this code from a tutorial
Do you have a class named Actors
with this code i was basically trying to set a Fov of 180 degree when a enemy would walk in that fov that turret would shoot the most closest enemy
but it is not working
idk why
yes it's in thi script https://gdl.space/uhajuhutej.cs
Look at the rigidbody. Does it have the word kinematic as the type?
That is a nested class
You need to access it though the other class. OR just not nest the class
You sure that the raycast does ignore the enemy?
wich mean (sorry i started like one mounth ago so i don't really understand evrything)
the bullet has the turretScript attached to it right?
You would either want to take the class and define it outside of DialogueTrigger or access it with DialogueTrigger.Actors
Your Actors class is inside the DialogueTrigger class
yes
it probably doesnt have to do anything with the kinematic
so to use it i have to definde the class actor in DialogueManager
Eh, I came in late. You asked so I was just trying to get the answer
It is currently in DialogueManager
Just make it NOT inside a class
If you want to reference it you need to either move it out of there or use DialogueManager to access it
hoooooo
ok i understand now
@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;
}
}
}
}
i need a FOV for the turret so it would only shoot the enemy in range
thanks for the code
you said that the bullet has this script attached?
yes
it is attached to turret or the bullet?
both
oh thats weird
The bullet should just have a script which moves it forward.
The turret should spawn the bullets facing the correct direction.
yes
i cant try to seaprate both
why?
i am seaprating the spawning from movement
this happend
my transform for spawn area also moved
the spawn area has the turretscript right?
yes
it has rigidbody too right?
right
well you move the rigidbody of it in the turretScript
if you havent changed it
look at the Start method
it is ok when i freeze the x y and Z position
yes
because that way the rigidbody doesnt move
btw you have only 1 enemy in your world?
no multiple
there are slimes wolves and worms
i will add more
ngl i think i have botherd you too much
sorry for that
no problem
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
nice
but it is a bit wonky
wdym by that
can anyone help me im trying to make a 2d sprite move up and down but i cant who knows how
What have you done so far
opps
!code
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
DOUBLE KILL
!code
It sometimes dose not spawn all of the enemies I will show you the code tomorrow
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ok
bye
rb.velocity = Input.GetAxis("Vertical")
that is what i have
ok
Where did you get this code from?
unity docs
ok
it says vertical does not exist
edit -> project settings -> axes
there should be vertical there
if there isnt reset it from here
ok
add rigidbody2d from the inspector
and do only rb= GetComponent<Rigidbody2D>()
dont forget to set isKinematic to true in the inspector
it should work tho
ok
ok
A Kinematic rigidbody does not respond to forces, so you cannot move it by setting the velocity
I believe that works in 2D
i think you can
Input.GetAxis(Vertical) 🤔
Man I just keep stepping on that rake of assuming 2D and 3D rigidbodies behave the same. One of these days I'm gonna need to actually make a 2D game
Just so I stop doing that
the really weird part is that you have static, dynamic, and kinematic rigidbodies
you forgot double quotes brother
You cannot. Kinematic rigidbodies can work with MovePosition though forgot it was 2d
"not working" is extremely vague
if you're getting a compile error, say that
This is a 2D rigidbody.
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)
Ah 2d. Yeah, I did see that way earlier
Honestly, that is one of the weirder differences between 2d and 3d imo
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.)
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
What is calling DoEnemyDeath? Isn't that the most important question?
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");
}
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
That's temporary, like I said I know the code is a mess.
that might help deal with the issue though
Yeah I will be reworking the code quite a bit, but just solved the issue. I had the assigning/spawning etc. of the shockwave outside of the if statement.
@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?
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
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
even if im using time.deltatime?
Yes.
i see, i'll change that immediately then
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
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
ignore my question, i made a spelling mistake
It lets you calculate the amount to change something by each frame
And it does make your game's overall behavior framerate-independent
"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: 165
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
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
hey 😦
You should not move the transform if you are planning on using a rigidbody.
why?
isnt rigid body just gravity?
It's much more than that.
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
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)
transform and vector are the only 2 methods im aware of
Neither of those are methods
both moved the sprite
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
you know what i meant, i wasnt using coding speach when i said method
I truly did not know what you meant.
velocity caused my sprite to roll like a ball, will the other 2 do that?
Freeze the x and z rotation on the rigidbody
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
just seen that while testing it, i thought it was due to my oval hitbox rather than a rectangle
Well, that IS part of it. But freezing the rotation on those axes will prevent it (unless you explicitly rotate them via code, which will still work)
In a physics simulation, round objects will certainly roll, so yes you are right about the cause
thanks
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;
}
Looks like you just changed the name of the local variable?
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)
Oh okay, yeah I am using both in the same script
Well, what is collision and what is other?
Oh, so yeah they do the same thing
I just need to be more consistent with my naming
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
Awesome, thank you so much
Anybody know how can I make a stake gun like in painkiller that pins enemies to the wall?
ragdoll
then add some simple joints, set the anchor pos to be the raycast point
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
other.gameObject.GetComponent<SpriteRenderer>().sprite = playerWeapon.sprite;```
how can i do this?
like switch the properties of the two variable
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
Some code somewhere is changing the sprite. It doesn't just change on its own
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);
}
} ```
You're setting the value directly to a value, which is overwriting whatever it was before. If you want the jump to work you probably need to keep the Y value the same
Yeah i discovered the cause, it was from the darn animator I duplicated it from
i thought it wouldve just worked out the resultant force, i guess not
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;
}
looks like you linked the wrong tires 🤷♂️
share the full script we might be able to help out more. Wouldn't hurt to share video as wel
i have already followed a different tut but had the same issues.
I mean it works like it should but the wheels just rotate in the wrong directions
then you linked your objects wrong
have probably incorrect pivot
how else we supposed to know whats wrong with that snippet alone
If you're directly managing velocity, forces don't really come into play unless you do the math yourself - and any forces applied via AddForce() will also be nullified. That said, if you just want to add the velocity to what's already there, it's just a matter of changing your = to +=
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
the wheels are all rotatet like they should as far as i know
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
press insert
Show us the inspector for one wheel
It looks like the wheels are starting with a 90 degree Y-axis rotation
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?
Now show the wheel collider's inspector
It looks like you have a 90 degree offset between the two
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
yeah but when i set the rotation to 0 they stay rotated like that
the colliders dont rotate just the model
There are two options here
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]
- Empty <-- rotation of [0,0,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.
np!
this is what I'd do if I absolutely had to maintain the current hierarchy
but otherwise, it's easier to just line your models up properly
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
If you're a beginner it's better to stick with the old input system as it is easier to learn
I'm curious. Why does an arrow work for the player here but not an equals sign like above for the moveDir?
these are two different things entirely.
the top one is a field with a field initializer.
The bottom one is defining a property with only a get function, and is defined as an expression-bodied member, returning this
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
I think I get it
the bottom one is a shorthand way of doing this really:
private Player GetPlayer() {
return this;
}```
so can I jsut write this instead of creating a player and using it?
Yes there's no reason for that property to exist, you can just use this
this is kind of a chicken and egg problem
"instead of creating a Player"
this is part of the Player class!
this.transform.position += new Vector3(moveDir.x, moveDir.y, 0f); should work if I understand you guys correctly
Yes, and it's identical to transform.position += new Vector3(moveDir.x, moveDir.y, 0f)
yes but you don't need this most of the time
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.
does anyone know how to put an item into the crafting slot by cliking on it like in this example?
just parent it to the transform, reset the localPos
I have a slot prefab so it is not about moving it to that area physically
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.
then what are you asking ?
the thing is there are inventory slots and crafting slots
think of Minecraft for example
ples help
Is it possible the raycast you are using is not checking for the parent object while being inside the center?
without drag and dropping, only by clicking, I want to pass the materials to the crafting station and depending on what I´ve introduced, it crafts something
feets not in the player model center
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.
so define a class named slot and add the clicking behavior
i use it to detect if player grounded at this moment or no
okay, let me see
in my happening raycast detects ground until 53 pos at y
mystics
I think it's fine to change the filename in either location, if your IDE is properly configured for Unity... Or at least I know that in least Visual Studio it's capable of updating the metadata file as well (which is the crux of maintaining your references), but I can't speak for other editors
Ok cool. I'll do a backup anyway but just wanted to double check.
I'm not really sure then. Sorry boss.
Awesome. Thanks again! Just a bit paranoid because of flashbacks. Some of my code relies on checking for materials and my friend who is doing the art updated some a while back and that broke a few things.
new to unity, following tutorial, not working, what is wrong with my declaration (3D rigidbody)?
Rigidbody rb; rb = GetComponent<RigidBody>();
what isn't working
"Rigidbody cannot be found" CS0246
spell it right
Look at the thing underlined in red in your IDE and see what's wrong with it
That alone isn't valid code either, but assuming you've just copied out what you think is the issue: Rigidbody is not the same as RigidBody:
https://docs.unity3d.com/ScriptReference/Rigidbody.html
are you using UnityEngine; and your script is child of monobehaviour?
ah
article doesn't specify the syntax.
Tutorial is using "Rigidbody2D".
show us the tutorial.
Yeah it's probably just the capitalization of the "b".
It does specify the syntax in the fact that it shows you how to spell the word right there
Syntax is how you spell something, the link I gave you spells it.
🤓 actually
Yes, I am using 3D
this is not a syntax error
@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
Correct. And you have to spell it right
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
in the tutorial he spells it wrong, so whoops haha
<Rigidbody2D>
No he doesn't
no hahaha
well, it is good to recognize the error that was made...
instead of just asserting that the tutorial was wrong
"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
bruh is that first part a bot or something?
😂
Didn't say it wasn't but no point getting hung up on that. It happens.
bros keeping score, and I added to it 
That is the idea, yes.
Sometimes you just need a second set of eyes.
No it's just the times I have personally been around when someone claims to have copied the tutorial exactly only to have not done that
meh it happens
or maybe I just need to get gud
or glasses
I actually need glasses badly
being poor is sucks
so this should work then?
Rigidbody3D rb; rb = GetComponent<Rigidbody3D>();
Where did you find a class named Rigidbody3D
I'm assuming its correcrt since it would be the 3D form of 2D
so you're guessing?
this isn't a puzzle game
You were linked to what to use:
#💻┃code-beginner message
Why make up a class instead of using the one whose documentation you were sent
If your IDE is properly configured, it should be suggesting possible values, and highlighting things that are wrong
True. Trust it helps.
the documentation doesnt specify which one to use in 3D vs 2D
When I started I didn't know you could configure and was just tabbing in and out of Unity.
I don't think there's a single Component in Unity, which uses 3D in its name. It's either ComponentName or ComponentName2D if it's 2D
The documentation is the 3D one
Behold there was an easier way.
That's the name
You can look at the name and see the name of the thing
🤯
I think it's 3D by default and you have to specifically specify 2D for 2D.
So just <Rigidbody>.
as someone who started unity development literally 4 hours ago, I did not know this
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
that's why I came here to ask, sorry if I haven't nailed down the naming conventions yet guys
<Rigidbody3D> isn't needed.
That's what you should do before asking here
Rigidbody4D on the other hand... 😎
In a beginner chat?
Yes.
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
Which tutorials can give you
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
I mean in the time it took you to link a bunch I just answered the question.
or someone can just throw me a bone and save me dozens of minutes looking for a two second answer
Which is what we call spoonfeeding around here. It is discouraged
perhaps you should consult #854851968446365696
You should definitely do the course I linked above
we call enablers
but now they're going to come back later and you're wasting your time
linking to documentation that tells you exactly what to do is a reasonable response #💻┃code-beginner message
Directly answering is spoonfeeding. Encouraging them to look at the docs is not.
I don't think saying "oh you mispelled something" is hand-holding.
you want to encourage people to learn to solve problems
i should point out that the answer was given almost immediately anyway
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.
its not an "Article" its literally the class for the 3d one
it tells you everything the class can do
I strongly recommend against any tutorials on youtube. Do the learn course before anything else
#💻┃code-beginner message
Explain to me how this helps build critical thought and I'll accept it. All I'm saying.
But you could've figured out that's not the case by looking at the syntax error it was throwing.
Also you've mentioned coming to Unity from Godot. I'm not sure, is Godot case insensitive if you think RigidBody is the same as Rigidbody?
that was just another oversight
I wasn't even sure the 3D part was correct.
which it wasnt
reading the api to learn how the class you want functions ?
what they learn if you do "do this , copy that"
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
It was a capitalization of the "b". It's not that deep.
that was the original problem, followed by more problems.
No one is saying that was an issue... simply pointing out a spelling error is not what is being called spoonfeeding
However, even then saying something like "consider the capitalization in the word" might have been more helpful in the long term, but that is whatever
I did say to configure the IDE to catch issues like that. I'm sure that would be considered as a good piece of long term advice.
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)```
Seems like it comes from the C++ backend, and that the parameters for clip.GetData() aren't checked on the C# side...
Are you sure startPosition is in range of the clip, ie. not negative nor too large so it falls out of the clip data length?
The subtraction you're doing a few lines above could yield a negative number for example
are rigidbodies deterministic?
Dynamic ones? Definitely not.
Kinematic, depends on you
shebb is embarking on the wild ride of a multiplayer fighting game
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?
Would probably have Image components there already and just set the sprites as needed
i am once again going insane, there must be a good way to do this
use a for loop
okay, I´ll try that
thanks!
can't really do a for loop there
I guess you could if they're consecutive enum values
Input.inputString maybe?
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
clip it to only numerical values
ah, there you go
good thought
oh, nice
I was going to suggest something awful
for (int why = (int) KeyCode.Alpha1; why < (int) KeyCode.Alpha9; ++why)
praetor's is much easier to grok
But this is more configurable and yeah easier to explain
also mine is wrong because it skips key code 9
just <=
Any idea
Why sound is not playing? When I collision occur
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?
Sure, that sounds reasonable.
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
I would create a Hurtbox component (or Hitbox -- "hurtbox" is more common in a fighting game where "hitbox" is used to attack)
A sphere or circle collider takes radius. It depends on the shape
It would specify how much it hurts to get hit in that spot
Collider doesn't have a way to adjust the size
It's a rectangle
Ooooh yeah, you're right
Thank you!
if (!Physics.Raycast(shootPoint, shootDirection, out var hit, maxRange, hurtboxMask))
return;
if (!hit.collider.TryGetComponent(out Hurtbox hurtbox)
return;
hurtbox.owner.Hurt(100 * hurtbox.damageScale);
something like that
Do you mean box or cube?
Box, 2D
Thanks. This is something along the lines of what I was thinking.
Just very doubtful of myself sometimes!
🙏
im making decent progress, i managed to play a 2 player game where all the inputs were perfectly recreated, i feel like im getting close to complete determinism
The namespace of all the classes is listed on the left and on each page fpor each class.
hint: it's not Cinemachine
yes outdated
Your IDE should suggest the correct namespace for you
it's not
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
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 ?
Write a script which stores the initial positions and rotations. Probably will need to set the velocity of everything to 0 as well if that's what you want
@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
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???
because this code, like all other code, doesn't take any in-engine time to run
this shows the exact problem you're having
why wouldn't it
Age is just a number, and so is deltaTime. Using deltaTime doesn't magically cause time to elapse in game.
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?
That's a really vague question that depends heavily on how your entire crafting and inventory systems work.
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
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
Agreed. Items should only sit mirrored in a staging area but remain in inventory until the player commits to the craft.
this is something like Mincraft's crafting table
which could make it more difficult to "reserve" items like that
slight problem, this throws index errors if i click a hotbar space that doesnt exist yet
that's what if statements are for friend
Okay, I´ll try, thanks
if i > heldFirearms.Count-1 ?
for (int i = 0; i < hobarKeys.Length && i < heldFireArms.Count; i++)```
would just update the for condition like this honestly
the thing is I am placing the objects right from my inventory into the table so the quantity lowers each time
I dont know how to create that staging area
or do cs if (i >= heldFireArms.Count) { PlayNoItemSound(); break; }
if you want to like... let the player know with a sound or something
the world is your oyster
thats working great, thanks!
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?
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);
}
}
It gives an error
and what is the error?
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?
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
You have to write a separate method that returns IEnumerator
(as you've already done)
No. You need a coroutine.
If you just ran Fade() in this example, nothing would happen
You have to pass the returned object to StartCoroutine.
as you have already done
all you have to do is put the for loop in the IEnumerator method
will do
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
Try changing the resolution of the Game View
see if your UI moves around or disappears
Mhm
Nope, doesn't work
You can't see it
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
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
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
wdym
You're trying to reference a Button. What Button
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
ah ok
thanks for letting me know that
i should also be able to figure out the component reference
whats the issue here?
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
GameManager.Instance.RNG = new Random((uint)replay.randomSeed);
when i create an RNG, does it immediately change the seed after i do this?
playerWeapon.sprite = other.gameObject.GetComponent<SpriteRenderer>().sprite;
other.gameObject.GetComponent<SpriteRenderer>().sprite = playerWeapon.sprite;
How do i do this but with it actually working
No. Nothing happens until you sample the RNG.
well, you'll have to explain what the problem you're having is
"actually working"?
is there a compile error?
It looks like you want to swap the two sprites
i want to switch value because im making a weapon pickup system
yes
Put the first sprite in a variable.
that way you can access it after you overwrite the player's weapon sprite
i see. could the changing of an unsigned int to a signed int possibly change the seed?
yo it works thanks
wait a second
nah its good
wait no this is weird
one second im gonna take time to think through this
hello
Can a child property have a way to know the identity of the scriptable object its a child of?
Not sure I understand? What are you trying to do?
I just needed a method that returns the parent from the child
really? i've got this replay system, and it seems like the rigidbodies follow the same path pretty consistently. the screenshot is two videos overlaid on top of each other, and they seem to be pixel perfect in terms of the path they follow.
I have a CardSO that houses an EventSO, I need to know the CardSO from EventSO
You mean from a GameObject?
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
Oh, okay. The parent/child is for a GameObject. You'd have to pass a reference to the EventSO . . .
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"
So i have the CardSO and an Event SO, problem is it doenst have a target right away
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
- who the target to the event is (if there is a need for a target)
- what kind of target it is
I believe 2) would be achievable with a TargetGenerator abstract class
- is what I can't get around, because I don't know to which card the event belongs to
I do not know. I made an assumption. I would trust your testing over what I said.
Maybe i should also do an non SOEvent class just so i could pass the owner to it at run time
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
Vector2 is 2 floats
you only passed 1
the name, vector2 🙂
so if i put vector 1 it will be fine?
vector1 is just a float
Did you check if there is such a thing
pulls out the ShaderGraphs stuff 
good thing they renamed all the vector1s into floats lol
how do i fix this error?
{
if (collision.gameObject.CompareTag("EnemySlap"))
{
S.Health -= 1;
}
}```
make it not null
this is the code related to the error
Take a look at the lines the errors are on, and find the thing that's null and make it not be that
how do we know
as it turns out it is not deterministic lol, weirdly enough at full speed fps there are some issues, like sometimes it bounces off and sometimes it doesnt, but that doesnt seem to happen at a low fps, which happens while i'm using the unity recorder.
which line
we can't read lines number from one snippet alone
line 51
which would be S.Health -= 1
Cool and how am I supposed to know what that is from what you've posted
Those two things appear to be unrelated to eachother based on the code provided alone. Without knowing if and how movementDirection is related to the rb's velocity, it doesn't appear to be something you could combine
S is null
oh so i didnt connect the thing
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
lol just post code properly next time
i dont know how else to do movement, every tutorial seems to be flawed in some way and codes online are like 50 lines long and i dont understand a single line of it
ok
if you're gonna show us the line number send the whole script or just tells us which one is line 51
i did that tho i said line 51 which would be then said the exact line
you said After which one was line 51 😉
thanks