#💻┃code-beginner
1 messages · Page 695 of 1
rn i just want to know what this error means
like, if i get a null reference, i know the error means "i have to assign something" but idk what this error even means because idk what an fmod sound instance is
it means that fmod failed to load the file. why that happens likely depends on a number of factors.
HELPPPP IM MID GAME JAM AND CANT GET THE DIALOGUE TO WORK
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NPCSystem : MonoBehaviour
{
bool player_detection = false;
// Update is called once per frame
void Update()
{
if(player_detection && Input.GetKeyDown(KeyCode.E))
{
print("PLEASE WORK!");
}
}
private void OnTriggerEnter(Collider other)
{
if(other.name == "Player")
{
player_detection = true;
}
}
private void OnTriggerExit(Collider other)
{
player_detection = false;
}
}
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
I just ended up reinstalling vscode and it worked, thanks
I don't see any dialogue in here. Which part of this script doesn't work?
Also, use a paste site or format small code blocks for easier reading . . .
when you enter trigger, it checks if the other is the player.
it doesnt check for the exit.
could it be that a non-player object is exiting?
its just a test to get it working, im trying to use a collider so that when its triggered and detects the player they can press a key that will then play the dialogue
what I was thinking
Do some debugging to see if the methods are being called at all and what objects are interacting with them.
If you're not getting interactions then follow this guide https://unity.huh.how/physics-messages
Does Unity Juniopr programming pathway teach you on how to do a Health system, in my case I need it as a stress level sorta thing like a percentage
is there any way for me to set the event system first selected field with code?
Are you referring to console messages as dialogues?
it doesn't teach you how to make specific systems, it teaches you how to code in unity
i think its because my player isnt an actual physical object
yes
no collider?
ok.. so basically it's a shot in the dark if you have Unioty 6 and wanting to learn how to do a health system
nope
lol u need a collider for trigger to work
so i have one on the NPC but not one on the player
do i need to add one to the player?
Try putting a log in the trigger enter and exit method
yes otherwise there is no trigger
they both need to collide
just bumping this because when I try to type the namespace EventSystem it says that namespace doesn't exist so I was wondering if it came under another name or something
I want to dev 2d games and is there a unity learn aspect with the coding side?
apart from the junior programming pathway
do the junior programming pathway, it teaches you how to code within the unity engine. 2d is the same as 3d in most aspects
You almost certainly should not be using a mesh collider. Use a capsule or something.
Doesn't your player have a rigid body setup or a character controller though? Or it is all direct transform manipulation and no physics at all?
be nice if they teach you more concepts like an advanced course on like actual systems
but it might be easier to just call .Select() on whatever object you want to select
there are individual tutorials for specific things. but you need to learn the basics before going and trying to make something specific otherwise you'll get lost trying to learn to make that specific thing
whenever you have an interaction between colliders (trigger or otherwise)
you need colliders on BOTH the objects
okay, thanks
ahhh ok, where would I go after learning the Junior pathway into 2D gaming stuff?
like being specifics
if you need it you can find individual tutorials on the learn site or with google
basically 2D Game Kit Advanced Topics?
if that is a specific tutorial, then sure i guess. i don't keep a list of tutorials to hand out to people who don't want to google for them. but focus on learning the basics first so you might have a chance of actually understanding how to do things without needing to find specific tutorials
I don't really have Computer Science knowlege only what Junior programming pathway is giving me
does anyone know the best way to do a grid of tiles where i can change the tiles during runtime
tilemap?
i thought u cant change them at runtime
why would you think that?
Make sure to check the scripting API page for the systems in question for the latest available tools
answered to bic but the api is good place to find inofrmation in general
you don't need computer science knowledge to make a health system. it's just a number and some methods . . .
Hi, in the case that somebody boots your game and their GPU doesn't support something you require, like Compute Shaders for example... what do you normally do? Should we be querying everything we need on startup and then show a message saying "GPU not supported" and quit? Currently, we're receiving exceptions about it occasionally in the cloud reporter.
Just needed to know where to go after the junior pathway like the API documentation, that's got every system right? for gamedev
the api documentation has the documentation for unity's api. it doesn't have tutorials for creating different systems which is what you were asking about
oh ok, is there any form of "Templates" or do I actually have to follow someone else doing said system on youtube?
seriously, stop worrying so much about what you may or may not need to do in the future. focus on learning the basics
I'm not, just asking since I'm part of a course
Heya everyone. Im kinda stuck on an issue right now. I got a giant square of 16x16x16. each time a part gets broken off I want to spawn a cube that falls of the object.
But when stress testing this I quickly come into issues with frame rates.
Ive tried object pooling
particle effects instead of gameobjects
Using drawmeshinstanced
But my frame rate always tanks. Is it just a call bottleneck. Im assuming its calling code like 2k~ time per second
did you look at the documentation?
i had a look but i couldnt find what i was looking for
maybe i was in the wrong place
also why would you want to change the sprite of a tile object and not just change what tile is there?
wasn't that what you wanted in the first place?
i think i mean that i have the tile map and i want to change what the image is on each tile with code
change the tile at the desired position
yeah
that is what i'm telling you to do instead of trying to change the sprite on the tile itself
okay
isd this where i should be looking https://docs.unity3d.com/Manual/tilemaps/tiles-for-tilemaps/tiles-landing.html
I would suggest looking into Tiled personally
yesterday I had a problem where my buttons weren't working, they weren't being highlighted, or pressed or anything no matter what I did. I still have this problem and I just don't know what could have caused it because it was definitely working before I returned to this project, the only thing I changed since then was starting to implement an inventory system into my game, so I don't know how that could affect anything
try the scripting api rather than the manual
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Tilemaps.Tilemap.html
thank you
is Udemy courses worth it?
for learning said script systems?
after the course ofcourse

but you're still getting ahead of yourself. you seem to be focusing on just getting through the basics rather than actually learning and internalizing them. if you actually learn from the junior programmer pathway then you won't really need any other courses, you might look up some tutorials for specific things you haven't figured out, but for the most part you will have the tools to make things on your own already. especially the simple "systems" you've asked about so far
if you keep going with this mindset of looking for the next best tutorial then you're just going to trap yourself in tutorial hell instead of actually making anything
What exactly becomes the bottleneck? How/what is the "square" made of and how have you implemented the logic for breaking off pieces? What code is called 2k times a second?
I do have an understanding, I just don't know to to actually do the said systems
and I am currently making a game of my own and connecting diffrent methods together, but I need to understand how to structure said systems instead of following someone that isn't using Unity 6 code examples
The profiler says that either the courotines are the bottle neck or the script.
when a object hits the cube it gets a cube from x -9999. Sets it active gives it a addforce and then send it back to the void to later be used again
Without the cubes its running at 400fps with the cubes its running at 30fps
Can you show what the pile of cubes looks like/explain why you need it?
right now its the basic unity cube with a material that has gpu instancing on it
Uhh its mostly added to give a bit of visual feedback
you're destroying the cube for money
4096 separate gameobjects especially if with separate scripts on each can easily become an bottleneck
well how it works right now
- a shooter shoots a bullet every frame (for debugging)
- a corotine (or whatever the spelling is) checks over a line multiple points till it hits the part of the cube
- the cube will break calling a script to break off the part
- the script will get get a cube from the pool give it a force and add it to a queue to be removed and send back to the pool when timer is over
now I got 9 shooters shooting each frame at a 16x16x16 cube
1000 individual Update()/coroutines will be less performant than 1 that executes over many transforms/game objects
unity calling to execute Update/ a coroutine has a cost
uhh I dont know if im just stupid. But... the cubes aren't the bottle neck anymore... it seems just destroying the cube itself is the bottle neck...
I dont know how I missed this I legit thought I ran it multiple times to see the fps and it seemed fine
not pooling them then?
Its the reconstruction of the cube that I think is causing the issues (my apolagies I though that this ran properly
I think im gonna have to go back to the drawing bord and limit the updates to the cube reconstruction or make it update only chunks
sorry for taking all of your time
if anyone unlikely happened to have this problem, I just replaced my eventsystem
Is there a cleaner way of telling another game object's script to do something?
For context:
I have a game manager with a script that reads inputs, and based on that input, it tells the player object to do something(If move right then character will move right).
Currently I'm doing the obj.getComponent<Script>() method, is that what I should be using?
ideally you would cache the reference to the component rather than calling GetComponent each time you need to access it, but yes. to communicate with other components you will need a reference to that component such as by calling GetComponent or a serialized field with the component assigned to that field
so I could create a serialized field of a component of a game obj?
Would it just be script?
how would I cache a reference?
I remembered how to call the script of the obj, so that solves that problem, but how would I cache things/
that's just storing the reference in a variable for reuse
that's one way to store a reference to an object, yes
are there better ways of doing it for future proofing/readability?
a serialized field is the best way to refer to another object
you can also check out this information for more ways to get a reference to another object https://unity.huh.how/references
alright, thanks
idk why I'm having so many coding problems today but can someone help me understand why my room transition code is happeneing exactly 5 times every single time no matter what?
{
public Vector3 cameraMinChange;
public Vector3 cameraMaxChange;
public Vector3 playerChange;
public PlayerMovement player;
private CameraMovement cam;
void Start()
{
player = GameObject.FindWithTag("Player").GetComponent<PlayerMovement>();
cam = Camera.main.GetComponent<CameraMovement>();
}
void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Player")
{
RoomMove(other);
}
}
public void RoomMove(Collider2D other)
{
cam.minPosition += cameraMinChange;
cam.maxPosition += cameraMaxChange;
other.transform.position += playerChange;
}
}
add debug logs
are there multiple colliders entering the trigger all with the Player tag?
also use the CompareTag method rather than string equality when comparing tags. it's slightly faster, but more importantly if throws relevant errors if a tag is misspelled or doesn't exist
there are exactly five colliders entering so yeah that was it thanks lmao
Packages/com.vrchat.avatars/Editor/VRCSDK/SDK3A/VRCSdkControlPanelAvatarBuilder.cs:2998)
VRC.SDK3A.Editor.VRCSdkControlPanelAvatarBuilder.OnBuildAndPublishAction () (at ./Packages/com.vrchat.avatars/Editor/VRCSDK/SDK3A/VRCSdkControlPanelAvatarBuilder.cs:2021)
System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_0 (System.Object state) (at <27124aa0e30a41659b903b822b959bc7>:0)
UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () (at <cb81df0c49c643b1a04d9fc6ccca2433>:0)
UnityEngine.UnitySynchronizationContext.Exec () (at <cb81df0c49c643b1a04d9fc6ccca2433>:0)
UnityEngine.UnitySynchronizationContext.ExecuteTasks () (at <cb81df0c49c643b1a04d9fc6ccca2433>:0)
can someone tell me how to fix this?
looks like a !vrchat specific issue to me
Join the growing VRChat community as you explore, play, and create the future of social VR! https://discord.com/invite/vrchat
i just thought since im usibng unity to upload an avatar then id need help with unity specifically
issues with the vr chat sdk and the like belong in the vr chat server
i appreciate the direction to the right server
Hey guys, let me know if there's a better place to ask, new to unity but not to coding. I am creating copies of a prefab but the script doesn't appear to be applying to the copies, only to the original (which is under the copies, there's a green one in there just covered)
toggleInventory.action.started += ToggleInventory; I'm really confused as to how this line could throw a NullReferenceException because the InputActionReference field I have is definitely filled in the inspector.
Debug.Log("Is toggleInventory null? " + (toggleInventory == null), this.gameObject);
sorry
im learning and im making a grid for my tactics system and it wont spawn the walls around it and i think i know the problem (the walls aren't linked in the tile script) but IDK how to fix it cause it wont let me just drag the game objects to the script for some dumb reason
trying to drag walls on left to spots on right but it just wont let me
you have to attach the script to something first
okay so thats not the probnlem them cause its attached and linked within the object
then why isnt my grid manager spawning the walls 😭
yes I know that it is null but the fact that it is null makes no sense because I clearly defined it in the inspector
I'm not sure you'd have to show your code
i can copy and paste it in a second
public class GridManager : MonoBehaviour
{
public int width = 5;
public int height = 5;
public GameObject tilePrefab;
private Tile[,] grid;
void Start()
{
GenerateGrid();
}
void GenerateGrid()
{
grid = new Tile[width, height];
for (int x = 0; x < width; x++)
{
for (int z = 0; z < height; z++)
{
Vector3 position = new Vector3(x, 0, z);
GameObject tileObject = Instantiate(tilePrefab, position, Quaternion.identity);
tileObject.name = $"Tile_{x}_{z}";
tileObject.transform.parent = this.transform;
Tile tile = tileObject.GetComponent<Tile>();
tile.gridPosition = new Vector2Int(x, z);
grid[x, z] = tile;
}
}
// Example wall between (2,2) and (2,3)
AddWall(2, 2, "north");
// Add outer walls
for (int x = 0; x < width; x++)
{
AddWall(x, height - 1, "north"); // Top edge
AddWall(x, 0, "south"); // Bottom edge
}
for (int z = 0; z < height; z++)
{
AddWall(0, z, "west"); // Left edge
AddWall(width - 1, z, "east"); // Right edge
}
}
void AddWall(int x, int z, string direction)
{
Tile tile = grid[x, z];
tile.SetWall(direction, true);
Vector2Int neighbor = GetNeighbor(x, z, direction);
if (IsInBounds(neighbor))
{
Tile neighborTile = grid[neighbor.x, neighbor.y];
neighborTile.SetWall(Opposite(direction), true);
}
}
Vector2Int GetNeighbor(int x, int z, string direction)
{
switch (direction)
{
case "north": return new Vector2Int(x, z + 1);
case "south": return new Vector2Int(x, z - 1);
case "east": return new Vector2Int(x + 1, z);
case "west": return new Vector2Int(x - 1, z);
default: return new Vector2Int(x, z);
}
}
string Opposite(string dir)
{
switch (dir)
{
case "north": return "south";
case "south": return "north";
case "east": return "west";
case "west": return "east";
default: return "";
}
}
bool IsInBounds(Vector2Int pos)
{
return pos.x >= 0 && pos.x < width && pos.y >= 0 && pos.y < height;
}
}
this is prolly rly bad code but it works up until the part where walls get involved
i think i got over zellous
are you getting any errors?
if not, do some debugging, see where it reaches
oh what you didn't mention cinemachine before
pretty sure this should go in #🎥┃cinemachine in that case
My bad
Is there a way to spawn prefabs onto a terrain like tree and grass with brush but all the component attach (like collider, script, etc) are still attach ?
inside a function, if i put return; inside a for loop does it terminate the for loop or the function???
return exits the method . . .
test it to see if it continues the loop or not . . .
If you only want to exit the loop, use break;
ty both ^^ i wanted to exit the function and wasnt sure if it was on a like, nested basis
On the other hand, break does respect nesting and will need to do it per nested loop
does any1 know why the text that is on this contact point doesnt show up ?
if (collision.gameObject.GetComponent<IDamageable>() != null)
{
// Get damagable object and damage by the inherited weapon's damage
damageable = collision.gameObject.GetComponent<IDamageable>();
damageable.TakeDamage(bulletDamage);
// Display a damage amount text on the collision area
contactPoint = collision.GetContact(0);
// Initiate bullet damage text onto contact point
damageText.text = bulletDamage.ToString();
bulletTextObject = Instantiate(damageText, contactPoint.point, Quaternion.identity, gameObject.transform.parent.transform);
bulletTextObject.gameObject.SetActive(true);
}```
I'm sure its something easy i'm just missing it
I'm using textmeshpro
Is it 2d or 3d text?
Also, you're setting the text before you instantiate it . . .
Which means you're setting (changing) the prefab text . . .
oops i mean to do bulletTextObject thanks for noticing
meant.*
bulletTextObject = Instantiate(damageText, contactPoint.point, Quaternion.identity, gameObject.transform.parent.transform);
bulletTextObject.text = bulletDamage.ToString();
bulletTextObject.gameObject.SetActive(true);```
that should do it
Hi! I'm trying to look online but i'm not finding anything useful, maybe I'm just bad at researching but welp
Is there a way to pause a method and wait until a key is pressed before continuing said method? if yes, how?
pliz ping me if anyone answers
coroutines
Use a coroutine, you can yield until a condition is true. It will check the condition every frame
You dont pause a method, this would entirely freeze your game
How would it work?
Mymethod(){
StartCoroutine(coroutine())
Debug.Log("thing")
}
coroutine(){
wait until input
}
it will Debug.Log("thing") when the input is pressed?
No, the log would be in the coroutine and after the yield (wait until)
Look at the docs on how it works, they have some examples too
ok!
Your MyMethod would not be affected in anyway and would complete immediately after calling StartCoroutine
Ohhh ok
yeah, kind of
excellent
Does any1 know how to make a 3d text keep looking at you?
textmeshpro to be exact
you can use a look at constraint to make it face a camera
https://docs.unity3d.com/6000.1/Documentation/Manual/class-LookAtConstraint.html
I see ill check it out
My character slides downhill when climbing a slope. How can I prevent this? (I already have a script that calculates the slope angle.)
i have questions about vuforia , anyone here si good at it ?
Rb or char controller
HELP:
when building the game error: "cannot create FMOD"
i have never used external FMOD
it works on previous builds
idk what made it happen
you gotta provide more than this
i dont really have more than this
it gives this error to pretty much every sfx in the game
well sending a photo of the actual error would help
wait a sec im trying to replicate
makes sense just by looking it up i can tell the FMOD is an audio system for games
which you must be using
its what unity uses for audio
i didnt use any FMOD other than what is native to unity
no?
wait
does it?
failed to replicate
so whats the problem then?
still gives the error
i tried to replicate in the editor
works fine there
im gonna try to fuck with the import settings, setting it to preload
again what error cause "cannot create FMOD" cannot be it
*turning off preload
is it like this? https://discussions.unity.com/t/error-cannot-create-fmod/179700
nah i dont use path to get the sound file
also you'll probably have more help in https://discordapp.com/channels/489222168727519232/531974372714610688
wait a sec im testing something
anyone know if its possible to render a certain layer (layer 8 in this example) above another model even if its inside it so its always in front, by using a shader or script or something
You can do this in URP pretty easily with the Render Object feature
im using birp
I believe you can just mess with the z-buffer depth
does anyone know how to fix this??? it used to be in 3d but i clicked a button now its in 2d please help 😭
doesnt BIRP material have a field for render queue ? I think you can also mess with that
bro this is unreal why are you asking in a unity code channel 🤔
wrong server AND wrong channel smh
yeah it does but it doesnt work in this case since i have another custom shader that is rendered in front of everything and if i render the player in front of this i would have to move the render queue of it which breaks the effect
but i found i fix thankfully thanks for your help though
If I'm making a controller that is going to be snapped to the nearest surface every frame, how should I move the player? Should I use teleportation, velocity, physics, or something else? What do people generally use when moving a normal controller without charactercontroller.move
i just submitted a game for a game jam but it crashes on webgl as soon as you click play, any ideas?
heres the link if anyone wants to test for me
is it bad practice to remove all listeners from the invokers' side rather than unsubscribing from the listeners' side?
- Normal C# event
how would the subscribers know to resubscribe on reenable?
im not sure about it being outright bad practice, but it definitely limits your options
imo just having both the subscribe and cleanup is easier to make sure it doesn't leak, but if you follow this pattern everywhere i guess that's not a problem
They shouldn't. It's just in case the object gets disabled early for whatever reason.
i feel like that's more of an OnDestroy thing then
also, do your subscribers never get disabled/destroyed?
if they don't unsubscribe themselves then you'd be calling stale callbacks
it can make sense in a few cases, but if you're destroying the object i dont know if you need to even set it to null. you cant just use this instead of unsubscribing though
Can anyone help me figure out what this sudden pitch bug is and how to fix it cause im lost
Cause im pulling up and out of nowhere it just pushes down hard like the last part or theres the first turn when i get out of the first turn and go straight it just dips down until i recover
Are you referring to the plane going down when you make sharp turns?
In any case, there's not much we can tell you without knowing how your plane controller works.
im trying to make walls fade in and out depending if they block a tile in my tile map but they arent fading. i have been trouble shooting for like an hour and got nothing. (i can send the code but its a giant ass wall)
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
How are you trying to fade them out?
changing them from opaque to transparant and lowering the A value
it only sends it as a txt file...
Too much text. Share it as large code blocks mentioned by the bot.
i have a ray that checks if its in the way of seeing a tile, if it is it changes it to transparant, if its not then it resets it to oqaue (or its supposed to)
Okay. That should work normally. How are you debugging it?
sendign a msg when it goes from transparant to opaque or vise versa
I wish unity would use BASIC, yes BASIC like in DarkBASICpro or AppGameKitStudio. Am tired of these cryptic lenguages.
And do you see the message?
its sending opaque messages but no transparant ones so im like wtf why is it not changing
and ive been tweaking things for like an hour and its changing nothing
Do you see the material of the object changing in the inspector at runtime?
yeah idk how to do this sorry im new
i dont think so. can u reword this like im 5 years old
Read the bot message again.
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
Do you know what an inspector is?
yeah but wdym by runtime
llike when i hit play?
A tool for sharing your source code with the world!
i think thats how you do it
okay so i checked
it is changed type from opaque to transparant but its still visible.
it looks like its changing internally but not visably... like its unsynced almost
Yes.
Take a screenshot. Or even a video of what's happening, including what you see in the inspector.
lmao enjoy a bad video from my phone recording my screen
Ok, but you're still to answer my first question.
yes it is the sudden pitch down on hard turns
Use OBS or similar software to record the screen. Heck, win11 even has a built-in feature for that.
i just found the win11 feature lol
this may just be a misunderstanding on how shaders work
cause it looks like it should work
Well, I'd assume it's this piece of code that is responsible for that
This should be working.
Can you pause the game when it's supposed to be transparent, switch to scene mode and make sure the correct object is selected(click it in the scene view)?
It would also help if you have gizmos enabled in the game tab.
sure
I want to make a path in a top down 2d game that's randomly generated, but i don't want to use a tile set. Does anyone have any recommendations for a method?
it crashed...
fuck. me.
time to redo a bunch of shit...
im going to actual do that tommorow and go to bed and have a mini breakdown
got back to where i was. here is what u asked for ( i couldnt find gizmo)
And the alpha is set correctly?
set to 78
What if you set it to 0 manually? Does it become entirely transparent?
I circled the gizmos button in the screenshot here: #💻┃code-beginner message
Can you take a similar screenshot/video with gizmos enabled?
It should show you gizmos of the selected object in the game tab, just like in the scene view.
You don't have gizmos enabled...
i clicked it 😭
But also, it seems like that wall is transparent
thats the one i changed manually
Okay.
the ones next to it are the exact same but just not done manually
all the blues are 78
think its on now
its light gray at least
Yeah. But I don't see any gizmos. Which might imply that this is not the selected object.
Actually, it seems like game view gizmos are broken in unity 6...
^ thats what it feels like
idk man. i feel like this isnt that complicated. everything says its working besides what its actually doing
its like watching someone do a math problem perfectly and forget to circle the awnser
they work fine in (6000.0.43f1)
testing in .47f URP now. And it doesn't seem to work. Throws a warning in the console too.
hmm odd
whats the problem?
How are you modifying the property? Are you using .material or .sharedMaterial?
my shawty code
you could've just used one of the websites !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
ope sorry
why does yloop never change??? the debug output says yloop is always 0
int yloop = 0;
int xloop = 0;
for (int i = 0; i < (item.sizeWidth * item.sizeHeight); i++)
{
// print("xloop is " + xloop);
print("yloop is " + yloop);
TilePositions celp = cellFromPos(posx + xloop, posy + yloop).GetComponent<TilePositions>();
celp.occupiedBy = item.gameObject.name;
celp.occupied = true;
xloop++;
if (xloop == item.sizeWidth--)
{
xloop = 0;
yloop++;
}
}
Can someone help me? It looks like its stuttering but I dont know why
Presumably, because it doesn't enter that if block where you increment it.
Use mp4 file so that we can see it in discord.
here
Likely an issue with how you rotate the camera.
can I send in the scipt?
i added a print and you are right, it never reaches that point. the problem is xloop does reach item.sizeWidth-- so i dont know why it isnt firing
just means that xloop == item.sizeWidth-- is never being true...🤷♂️
Debug the values of these veriables to confirm that.
i know thats not true in this case though, the value here is 3 while sizeWidth is 4
I don't see sizeWidth in this log.
Print all the relevant values in the same log to avoid confusion.
great point actually
just use a
Debug.Log($"xloop = {xloop}, item.sizeWidth-- = {item.sizeWidth--}");
No, don't include the decrement in the log, as that would alter the logic.
would it?
Yes. You'd decrement sizeWidth one extra time.
Or wait a moment. I think I had a brain fart... Let me check somethign real quick.
example of what im talking about
nope it does
my bad :/
print("sizewidth is " + item.sizeWidth + ", xloop is " + xloop);
if (xloop == item.sizeWidth--)
{
yloop++;
xloop = 0;
}
print?
Yeah. It does. Started doubting myself for a moment there.
print is the same thing as debug.log as far as im aware(?)
seems so just also outputs some extra after, didn't know unity had a base print function call
ye
either way: the if statement SHOULD be fulfilled there because 2-1 = 1
but its not
interestingly enough it doesn't show the decrease when outputted but only after (at least not for c# itself)
variable-- would presumably decrement after the comparison.🤔
Try --item.sizeWidth. Or even better - don't do inline decrementation in the condition itself.
Also, add a log inside the if block
yeah i think this would be it based off the test i tried (shown in the photo i just sent)
Yes. Honestly, I'd avoid using syntax that you don't 100% know how it works.
Or research it.
wanna send the code snippet
Add a log/pring inside the if block
alright
And share the logs where you think the condition should be true
should the item.sizeWidth be reduced by one if the if statement is true? cause it is
no
item.sizeWidth should not change in any case
Well, it does now
Again, don't use syntax sugar that you don't entirely comprehend
and how to fix it
i would not have used it that way if i knew it worked different 💔
i got the walls to work decenetly enough for a proof of concept (still very bugged but it should be fine. it doesnt need to be perfect it needs to be fun)
the result is ALMOST there so i think i can get the rest on my own, thank you very much
if u move the camera around u can fix it easily so ima call it there and go to sleep. thx for all the help i owe u all
That's part of learning the basics and reading documentation.
me everytime my code doesn't work, but then im too lazy to play test it to see if it works or is fun
Did you end up swapping materials? Or modifying the existing ones to be transparent?
im just trying to make a decent beta that shows the core mechanics so i can get feedback on the actual idea before i sink money into it
i plan on actually hiring a coder if i get good enough feedback on the beta (i doubt i will but maybe)
Swapping was a lot easier
The raytracing is being weird so I tried to make it set all connecting walls of the same orientation to also be the transparent material and that works decently enough
I’d say 75% of the time it doesn’t bug a little but wiggling the camera resets it
so it’s finnnnee
guys i beg and I plead. I'm incredibly new to coding and have been trying for 10 god forsaken hours to make a UI image literally fade in, pause, then fade out upon the game starting up. I have found absolutely 0 tutorials for this online, I have scoured the deep recesses of planet earth and I CAN'T find a way to do what seemed oh, so simple to my baby naive mind. my life is yours is you can help me
I've no clue how the heck were you searching. Google reveals many results, with the first video being exactly what you're trying to do...
i've already watched that video. to my dismay it teaches you how to fade when activated by a button and not automatically
its all activated by triggers and I don't know how to do it without
changing a function call from being called on a button to being called by void Start() isn't that hard
Great, so now you just need to learn how to do something automatically.
my friend I started using C# 3 days ago. I feel like some hostility is permeating and I am sorry for my ignorance lads
I recommend going over the beginner pathways on unity !learn. It would make a lot of stuff so much more easier for you.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
sadly don't have the time, I'm on a time crunch and therefore am forcing myself to rawdog a lot of the subjects, it was going well until I faced the dreaded fading
thanks for the advice though
You'd be suprised
I don't know what hurry you're in, but it's probably not a good justification for not learning properly
Running through something like https://www.learncs.org/ is gonna be a lot faster than trying to bruteforce it
just change ShowUI() into Start() and add an extra line to it being
myUIGroup.alpha = 0;
then remove the buttons
you simply arent gonna find tutorials that are exactly what you need. You found a tutorial that does what you want, but because it used a button, you are unable to use any of it.
So you either learn how to adapt the code to not use a button or keep searching while not learning anything
i get that lads and to be completely clear my current methods of learning are a temporary measure. I'm well aware I'll get more out of it by learning from basics in the long run, only problem is my current run is incredibly short, and thus requires shortcuts to complete
once im out of a pressurised environment, I'll return to a more structured form of learning
it doesnt matter that your timeline is short. You have a tutorial that shows you what you need to do, and you arent using it
Forsure, And theres no judgement for that but the kind of help your asking for isn't really the kind of help that gets provided here
ignoring that i gave the answer :/
apologies lads, wasn't really sure where else to go, also thanks a bunch magic
Yes because your not really meant to spoonfeed here
also i'm learning blender aside unity which isn't helping with my immense plate right now
fair
this isnt really an answer either considering it wouldnt fade out. then they would pop up again for you to write the code for them
all they asked for was fading in
oh wait nvm im blind
oh well
im sure they can figure it out im about to go to bed as it's ~1:30am
Ouh, I didn't know that scrollbar on the list could appear. I kinda hate it, thank you, can I just tell it to not do that? lol
What differences actually have crossFade vs crossFadeInFixedTime
i know is that one changes Animator's states using times in seconds, but my problem is, what specific things may occur with one and the other
I may venture to say crossFase is based on frames on FixedTime uses the timeline instead?
Hey guys I need some help, I'm trying to make the 3D TextMeshPro text look at the player, and it's not working, im not sure why.
{
// Set world object to look at
damageTextConstraintSource.sourceTransform = Camera.main.transform;
damageTextConstraint.AddSource(damageTextConstraintSource);
// Enable component/s
damageTextConstraint.enabled = true;
damageText.enabled = true;
damageText.gameObject.SetActive(true);
Debug.Log("Enabled constraint.");
}```
For the record: I nullify the Text's parents so it's parentless for now
The weight on the right hand side of the Sources list is 0
oh, i thought that was the source number
lmaooo
The text is indeed looking at me just in a weird mirrored/inverted/rotated angle
@north kiln you got an idea on how to fix it?
I tried declaring:
damageTextObject.transform.localEulerAngles = new Vector3(0, 180f, 0);```
Fixed the upside down issue by unchecking "Use Up Object" but it's still inverted now, i'll try rotating it wiht a vector
The world up object seems to work via the vector towards the object, not it's up
there's a rotation offset in the constraint settings, just use that
can i ask what the main difference is between the old and new unity input system?
The new one is properly configurable and rebindable at runtime in a reasonable way
the old one isn't, it supports everything via strings, and is pretty terrible to work with outside of basic use cases
thanks i just did, works
I'm a beginner, should I try to learn and implement the new input system?
for keybind settings i could see it being poor but i perfer it over the new input system otherwise
You can still write code very close to the old system without it being constrained by strings and other crap
any ideas on how to make the text be viewed regardless ?
gotcha thanks
use an overlay cam that only renders the layer that your text uses
on my main camera itself?
an overlay camera is a different camera
I added a camera as a child to my main camera, and put it on render type overlay
Where can i choose a layer?
volume mask?
where it says culling mask
oh
Hey, good morning/afternoon!
I’m having a bit of trouble getting my assets to fit properly on my grid in Unity. Would anyone be able to help me out with this? I’d really appreciate it.
it isnt working, maybe because the text itself doesnt have a parent?
should it be inside a canvas? its a 3d textmeshpro
That has nothing to do with it. Look up a tutorial instead of doing random stuff
World space text doesn't need a canvas
Now I assume you want general UI which does need a canvas
ok then im just stupid
Do you want your text to be like a main menu?
Or do you want it to be an object in your 3d world?
No i jsut want the text to be displayed and not clipped by the cube itself
Then pick a type
a 3d text that is displayed on where the bullet hit, damage text
everything is working other than the text clipping with the cube itself
i made an overlay camera but for some reason it doesnt render the text..
So yes, you will need to use an overlay camera like I said before
Show you text prefab and show your overlay camera inspector
Make sure that your camera excludes the UI layer from its culling mask
i did, ill check it real quick
Main camera*
that is my main camera culling mask
this is my overlay camera culling mask
for some reason the overlay camera doesnt seem to render
completely my bad
stuck was empty
XDFDD
happens to the best of us
Is this like.... intended? Why can I not rename this particular asset but I can all the rest?
Is this unity being weird or do I have something toggled that I didn't even notice?
hey guys, just a general question here, if I'm making a custom map editor for my game would it make sense to save the map data using json? the map data would consist of a couple of single channel 2d textures for the terrain, and some stuff for road nodes, building positions etc.
would it be a bad idea to use json considering the terrain textures might have a resolution exceeding 1000x1000? or is it fine
Are you implying you want to store the texture itself in the json?
more like a 2d array of floats
but yea
a heightmap
Why not store that as an image 😄
putting it all in the one json file seemed like a more elegant solution
plus eventually I want people to be able to load custom maps when they join someone elses game
From my understanding doing this via a json is gonna be worse than a image but i could be mistaken
i don't think handling a whole texture via json serialization is a good idea no
How is it more elegant, you would be basically recreating what an image is in your json file. Then youd have to manually create the texture and supply this to the terrain in the end.
Its easier to just reference a local file name. Also the user could at least edit the texture in an existing program if they wanted
I mean people could just copy and paste a json and boom there it is u have the map
What? That doesn't relate to anything I said
I mean for the end user u just copy and paste someth and boom u have the map
Repeating the same thing doesnt make it relate to what I said still.
You're avoiding using an image for no reason
I'm asking if its really necessarry tho
like if its just a 2d array of floats
Nothing is necessary. You could ask them to manually type in all 1 million floats for your 1000x1000 array.
Some things dont make sense to do regardless
When your users ask why they cant edit the texture in image editing software, you can gladly explain to them you opted to avoid an image so you could write 1 million floats to a json file
so if I use JsonUtility.FromJson it will still give me my map data?
yea but... who would do that
People who want to do it.
Still, what's your reason for avoiding just loading an image?
Youre already loading the json file
you could just zip the multiple files
seems simpler if I can just use a single json file to store everything
then its "1" file 😄
I see
Simpler yet you suddenly need to manually write and read all the floats. Then somehow supply this to a terrain as a texture
So you save 2 lines of code not loading an image, so you can spend a lot more time trying to process a bunch of floats as an image
I don't know what you mean by this
the terrain sets the height of vertices in a mesh using a 2d float array
Is it purely just height data youre storing? Your initial message said textures, which i would assume includes the colors actually drawn into the terrain
nooo no
just a height map
Writing it and reading it as json might still be slow, but you could setup a test case pretty easily and see roughly how long it takes on your pc.
For loading the entire map, you could usually get away with a small delay of loading time with a loading screen on top
I see... I'm also going to have other height maps for foliage and also foliage cutoff so it might not work but I'll test it out and see if it works
I think I'll try storing the data as integers and see if that's a lot faster
Realistically I would test a few of those 2d arrays at once, using whatever you consider the upperbound to be. Then test it with writing as an image and see if there's a difference. The profiler can easily show you if there's a difference
Both are 4 bytes anyways. For an int you would be converting it to float so this would be slower
the other issue is that I have pretty ambitious optimisation goals, a lot of my players are on craptops so if json is significantly slower I'll have to use images anyway
oh thanks I thought it would be faster
at the end of the day just seems weird to not store an image as an image tbh
also for a foliage cutoff map using booleans wouldn't be faster in json format right?
just kinda seems like if that would be better people would be doing that aha 😅
well yea but my game is very simple graphically and the only data the images are storing is a simple height map
it looks like CS 1.6
sure but that's not really relevant to my point
image file types are probably just going to be better at storing images than string file types
if the difference matters profile sure but then the question just comes down to do you prefer doing it the worse way in order to cram an image into a json file
well yea but the heightmap is a 2d float array when working in the editor itself, not an image
but ig I could convert it to a texture
Storing anything non human readable in json is a terrible idea. Just use your own simple binary format
does any1 have a way of coding a text animation Y to go up slowly
i cant use the animation tab becuase the text Y is dynamic and i want it to just go up from its own Y and not from 0
give it a parent an make the parents Y dynamic instead
so you can animate the texts y in relation to the parent with the animation tab
hello everyone
i am new in unity .can anyone help me .i want to make a game like chagchal .
i add a ss of game. please please help me
and goat move will be an ai how to made this algorithm.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
hi!
public IEnumerator PlayerDone(){
bool flag=false;
if(Input.GetKeyDown(KeyCode.Space)){
flag=true;
}
yield return new WaitUntil(flag==true);
MobTurn0();
}```
Is this coroutine working as intended?
Will it WaitUntil the space key is pressed to execute the MobTurn0() method?
Put the input into an update()
no. also that wouldn't even compile
Also this
lol aight
hi, i have a question, this checks the player's distance from the enemy on all 2D-Sides, or only horizontally?
i mean, what if the player were in the same position horizontally but not vertically, and if is too close it changes state, it will still trigger it despite not being on the same height??
protected void DistanciaObjetivo()
{
distancia = objetivo.position.x - transform.position.x;
distanciaAbsoluta = Mathf.Abs(distancia);
}```
You're only checking on the x axis . . .
i know...
the thing is
how i can make it check the x and y axis at the same time
holup i think i know how
new Vector2(objetivo.position.x, objetivo.position.y),
new Vector2(transform.position.x, transform.position.y)
);```
like this?
I'm doing the junior programmer pathway on the unity site and one of the challenges is to get a planes propeller to spin, which I can do no problem, I just can't get it to spin fast. I mean, I can, just not when using deltaTime, but I know I should use that. Anyone know what I'm doing wrong?
using UnityEngine;
public class PropellerSpin : MonoBehaviour
{
public float spinSpeed = 300f;
// Update is called once per frame
void Update()
{
transform.Rotate(Vector3.forward, spinSpeed * Time.deltaTime);
}
}```
Change the spinSpeed in the inspector if you want to see the new changes
Using deltaTime is correct
Okay, I see. I was changing the speed in the script but I guess that doesn't update it in the inspector, which was why even setting it to 10000 didn't make a difference
I thought changing the script would also set the public variable when I went back into unity and it starts compiling
once the value is on a game object the serialized takes precedence in the inspector . If you re-added the script or right click to reset script it will show the new value from script (this is the initializer)
Okay, that's useful to know
Something I wanna understand because it's not really clear, sometimes you'll get this code with a comma after the Vector, sometimes with a mathmatical symbol. What is the actual difference?
transform.Rotate(Vector3.forward, spinSpeed * Time.deltaTime);
transform.Rotate(Vector3.forward * spinSpeed * Time.deltaTime);
The tutorial kinda flips around with if it wants to use a comma or not
those are using two different overloads of the same method, which you can see in the documentation. the first is using public void Rotate(Vector3 axis, float angle); which specifies the axis to rotate around, and the rotation to apply. the second is using public void Rotate(Vector3 eulers); which is just the rotation for every axis to apply
mathematically it is the exact same thing
Hey there, does anyone know how I could use GetKeyDown to make it so a combination of keys triggers some action (a sound), please?
Is there a way to store multiple "GetKeyDown" into a group, and then tell Unity that when this group is activated, it triggers the sound?
you wouldn't want to use GetKeyDown for that, GetKeyDown is only true for the very first frame that a key is pressed and it's unlikely that multiple keys will be pressed all exactly within the same frame.
you would either want to just check if all of the relevant keys are currently pressed at the same time, or when one of the keys is pressed start listening for the others but only within a short amount of time to ensure that it is pressed as a "combination" and not accidentally triggered by holding one key down and then several seconds later happening to press the others.
alternatively, i think the input system might have some better ways to handle key combos instead of doing things manually with the input manager (which is what the Input class is part of)
public void OnCollisionEnter2D(Collision2D collision)
{
Destroy(gameObject);
CanPortal = true;
}
how can i make this collision, only work after another class
what does it mean to "only work after another class"
sorry, i phrased that wrong. Basically, im shooting a bullet, and after that bullet collides with the object. I want to place a portal there. However, the adding the portal method is in another class.
Is the class any class or is that on the object you just hit?
so call that method on that other class in this collision message
make a reference to the object you want to call method from
I see. yeah, that would more be to start listening for others as I don't want the combination to be an all-at-once one. so how can I do that precisely?
I didn't know about an input system, I'll look into that.
yeah, but i think its trying to place the portal before the collision, and so "CanPortal" is false and wouldnt work. Is there a way to make it happen after the collision
if you're directly calling the method from this collision message you don't need that useless bool
{
GameObject newBullet = Instantiate(PortalBullet, transform.position, transform.rotation).gameObject;
newBullet.GetComponent<PortalBullet>().Player = this.Player; // Assign Player reference
if (PortalBullet.GetComponent<PortalBullet>().CanPortal == true)
{
shootBlue();
}
}
you're not even checking the right instance for that bool either, you're checking on the prefab but only changing it on the instantiated objects. so it's even more useless than i thought it was
i would strongly recommend just using the input system for this (and all input really).
if you don't want to learn how to use it though, then you best get to googling how to do key combinations using the input manager
Is it a fixed sequence of keys or can the order be switched?
it doesn't sound like a sequence but rather just a combo like ctrl+c
how do i check for the right instance
He said they dont need to be in the same frame so I assumed a sequence
that was in response to me saying they cannot realistically expect to have any combination of keys pressed all at exactly the same frame because they were talking about using GetKeyDown
so you're just gonna ignore the actual advice i gave you that would remove the need for this bool?
Ah alright, yeah if its a keycombo input system will be your best friend
no it is fixed
like A then R then Y then O
ohhh i get you noww. Sorry i misunderstood you the first time. Thanks
I'll get to learning then, thanks
by the way, is Visual Scripting good for a beginner? because I feel like there really aren't that many visual scripting tutorials on a specific matter, whereas there is much content when it comes to C#
Oh so it is a sequence, then you can use coroutines that basically wait for each distinct keypress until going for the next step
its good for learning logic and the compoonents unity has, but in the long run its simpler to use C#
Visual scripting is not really big right now in Unity and until the graph toolkit is fully released dont expect it to grow much. It is there and usable but id call it niche
alright, thanks
and I'll look into that
Guys I need help with trying to make a cutscene when the player picks up an item
Whats your Problem with it right now?
do you know how too
something like Timeline will make the sequence easier cause you can combine multiple componentns like Animator / Sound etc.
otherwise Code + Animator to do basically the same thing
im confused tho like how do I get the animation to play whenever you pick up the item
That sounds like you dont have fundamentals of Unity down.. that task you are trying to do is like 10 subtasks
??? wydm subtask
There is no feature in Unity to just play a cutscene (unless you want to play a video)
You have to do several things to make a "cutscene" happen
what bruh thats dumb I cant play a cutscene when I pickup a item
Animate the camera, maybe remove UI, disable Player controls, enable post effects
if you have a video sure you can just "plug and play" it but A cutscene is literally a sequence of events happening usually
But I have a plan for it so that a door breaks down and you can enter but if the video cutscene cant do that tho for the real game
which is why you need to compose the sequence yourslef like like wiht timeline
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
I read it before tho
so whats the problem ?
so make one lol
but I want it to start when it picks up the item
so then use c# code to start the timeline
I dont wanna use timeline because I dont know how too
this is being useless
sounds like you want all the benefit of a result without putting any actual work
if thats the case why are you in gamedev ?
Yes, if you are unwilling to learn it indeed is
So I made an InputAction called jumpPlayer and set it to this with the key binding being space :
jumpPlayer = playerInput.actions.FindAction("Jump");
If I press space it returns a value of 1 and I use that to jump :
jumpDirection = new Vector3(0, jumpPlayer.ReadValue<float>(), 0);
rb.AddForce(jumpDirection * jumpForce, ForceMode.Impulse);
the problem is that the value stays at 1 while the key is held down, making it so my character keeps jumping as long as the key is held down. How can I make it so it only returns a value of 1 the moment I press and then goes back to 0 until I press again ?
I can post the entire movement script if you want to see it more in detail.
well look like I aint making a game
regardless, anything you do in life requires some level of effort and learning . Otherwise pay someone to do it for you
even with jump being set to press only it still repeats the action as long as the key is held down, can anyone help with that ?
Is action type set to button ?
yup
It's my first time using this new Input system so i'm still strugglign with it
I just want to make it so it registers this action only once per press and doesnt keep registering it while the button is still held down
you should probably subscribe to the performed event then call jump from there
And check if the Action type is the one for started pressing
Can you show me an example, cuz honestly I dont understand that
Not sure what the name for it was rn
action type for jumping is set to Button
jump.performed += MyMethodWhenJumpPressed;
put this in OnEnable / After you have done FindAction()
private void MyMethodWhenJumpPressed(InputAction.CallbackContext context)
{
Jump();
}```
obviously you want to change the name
its also good practice to unsubscribe events
OnDisable() / OnDestroy()
jump.performed -= MyMethodWhenJumpPressed;
Tbh I have no idea what to do here, i'm completey lost
is there a way I can paste the entire script here without it taking the entire screen ?
I spoon fed you the code, just copy it
use links in !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
look where you call FindAction() literally underneath it , subscribe to its event performed after that you assign a method to it, in my example MyMethodWhenJumpPressed
you need InputAction.CallbackContext context in the paremeters because the method expects it
Hey! I’m trying to make a 2D aiming system in a 3D space where the gun would point in the direction for the mouse, kinda like “getting over it”, how could I do that?
I tried using ray casting so that it would follow the mouse position but it doesn’t seem to behave the way I want it to
dont see how raycast would help here
What could I use instead?
camera.main.ScreenToWorldPoint
if you're using Perspective camera though you would be better off using a Plane
I tried that as well, it doesn’t behave correctly🥲
are you using ortho or perspective cam?
why did you put the method in FixedUpdate, nowhere in my spoon fed code did I put tat there
also why didnt you use the links in code bot msg.. dont use screenshots for code
not even sure whats going on here jumpDirection = new Vector3(0, jumpPlayer.ReadValue<float>(), 0);
you don't need that at all
I see, I use orthographic
idk man i couldnt find a tutorial to program movement with the new input system
then yes this would work perfectly fine
Vector3 worldPos = camera.main.ScreenToWorldPoint(Input.mousePosition)
worldPos.z = 0
it works for jumping but i still have the problem with the character continuously jumping if the button is held down
Do I attach the script to the gun? Because what I did is creating a pivot point and made the gun its child
And the script went on the pivot
put the script where you want, just make the proper reference to the pivot
I see, I’ll try that thank you🙂
send the current code cause that should not be happening
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
ops wrong thing
np. from there you can just assign the direction
pivotTransform.right = (mousePos - pivotTransform.position).normalized
use Up if your default pointing direction is up (green arrow)
That's the code before writing anything you said
why did you send the old one ?
send the updated code with the changes I told you to make
and save them
Put a log Inside MyMethodWhenJumpPressed
save , hold Jump key in the game, how many times does the log print
make sure collapse is unchecked in Consoel window
what value do i put in the log ?
Shouldn't I put MyMethodWhenJumpPressed(); in update or fixedupdate ? because i'm not getting anything from the log rn
no, the whole point of events is not to "poll" (continuously checking)
nvm it gives me an error
whats the error
There is no argument given that corresponds to the required parameter 'context' of 'PlayerMovement.MyMethodWhenJumpPressed(InputAction.CallbackContext)'
let me see the new code you wrote
how does this work?
jumpPlayer.performed += MyMethodWhenJumpPressed;
when the Event is called (button pressed) it Calls that method on its own
because it is "subscribed" to that event
would it check if the button is pressed cause it's in OnEnable() and not Update()?
private void OnEnable()
{
playerMovement.Enable();
jumpPlayer.performed += MyMethodWhenJumpPressed;
}
no you're "subscribing" to that event and reacting to it with a method, and subscribing only needs to be done once.
once you subscribe to it, it will keep subscribed until you tell it not to
ah alright then is the OnEnable called if it was enabled from the start?
like Subscribing to a youtube channel, you only do it once, not every time you want to watch a video from that channel
yeah i get what you mean
OnEnable happens once like Start (assuming you dont make it gameObject.SetActive = false/true)
which line
Readded it to fixedupdate https://paste.ofcode.org/33TygsWJtx6cinKuSyh77Sm
line 81
jesus christ
why did you put that method in fixedupdate
I told you earlier you don't need that there
also sending the code to me different than something else you made :🤦♂️
cuz you asked me about the error
that makes no sense..
the error happened because you put that there in fixedupdate where nowhere did I ever say to put that there
you asked which line gave me the error so I readded it to fixedupdate to see which line
no.. that still makes no sense...
put the code how it was when you sent this
https://paste.ofcode.org/ysCwgAV6DrR4AGMUewsuGg
SAVE then Test it, if THAT somehow gives error then send the LINE # and dont change anything on your own
the error is telling you you're trying to call MyMethodWhenJumpPressed() without the required context and thats not something you should be putting manually, unity fills that in from the event
did it, no errors but pressing the jump button doesnt do anything
not even logging
show the console window after you've pressed jump
only error i get is this
okay now it makes sense
couldnt figure out a way to solve that too
but my movement still worked fine when i was having it so i ignored it
this is running OnEnable before the Start (this is normal)
it errors because you do FindAction in Start which is AFTER you run the subscribing to event so it has no idea which InputAction jumpPlayer is
thats why I said to put += AFTER you called FindAction.
wait huh why are you enabling it's own code in itself? nvm, you just have the script with the same name as a variable (minus a capital)
so either put FindAction("Jump") in Awake or put the FindAction in OnEnable before doing jumpPlayer.performed
you might need a course on basic c# / unity
learning how references work
I put all of it in start and it works now
void Start()
{
rb = GetComponent<Rigidbody>();
playerInput = GetComponent<PlayerInput>();
movePlayer = playerInput.actions.FindAction("Move");
moveCamera = playerInput.actions.FindAction("Look");
jumpPlayer = playerInput.actions.FindAction("Jump");
jumpPlayer.performed += MyMethodWhenJumpPressed;
playerMovement = playerInput.actions.FindActionMap("Movement");
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
private void OnEnable()
{
playerMovement.Enable();
}
private void OnDisable()
{
playerMovement.Disable();
}
now the jumping works only when i press
it's weird tho that it logs the action twice, once on press and once on release
!code please
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
but the actual movement still works fine
ye mb
make sure you put trigger behavior to Press only
@rich adder Thanks a lot man, i'll keep trying to read about what you just showed me cuz i still dont fully understand, but atleast now the movements works
it's already set to that which is why i'm confused
and yes I am still very new to C# and unity
did you like save the action map when you did that? it shouldnt be happening on release if you have Press only
are you sure its the LOG being also printed on release too
i fixed it, the issue seeme so be that I added the trigger behavior for both the action and binding
so I removed it from action and kept it only in the binding
no it only logs on press
Do you think I should go learn C# more in depth before even attempting to use Unity or is it fine if I just kinda learn along the way ?
well its always best to learn c# basics first before unity, doesnt mean you cant learn the same things in unity, but jumping onto an entire game wont be easy without fundamentals first. So You should aim to learn the basics first and test it in unity , put the projects on hold and just do some learning projects where you just eperiment what you learned
Unity at the end of the day uses C# API so you are still using regular c# (obv) , unity has specific methods/objects to learn that are Unity only but they are still just defined as c# objects . The only thing that changes is unity specific concepts
like GameObject, Components, etc.
the Unity Learn courses are good introduction to both, but there is also the Microsoft learn site where you can get more in depth learning general c# (check pins)
Alright, first off what are the basics I should learn before even getting into Unity ?
Also I'm not really trying to make a full game rn because i know it's unrealistic, my plan is to make a couple of small projects each focusing on specific mechanics like movement, shooting, turn-based combat, etc so I can then maybe combine everything i've learn to try and make a small game
Dont know if my method is the best but i feel liek it could work, so far when it comes to C# i've mainly just learned how to deal with basic variables (bool, float, arrays, etc) and how to make classes and create instances of those classes
most of these are the basics
https://web.archive.org/web/20240331070926/https://learn.unity.com/project/beginner-gameplay-scripting
i'm sure it's nearly not enought right
Oh yeah i forgot about those, thanks for sending this
why is it in wayback machine tho ?
did they delete the tutorials ?
because the one in the pins isnt working for some reason, I think unity somehow took it down or messed up redirect , as usual....
ah ok, well thanks a lot man, i admire your patience with me
they're also in a Youtube playlist on the Unity channel
this isn't working either? !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
learn site is working fine
oh ok nvm then
https://learn.unity.com/project/beginner-gameplay-scripting
now redirects to https://learn.unity.com/projects for some reason..
typical unity things ™
i think they moved it to the essentials pathway
unity likes to quietly do shit sometimes 🤷♂️
In any case thanks a lot again for the help, it was really humbling. I'll go play some battlefield now, you fellas have a nice rest of your day :D
@rich adder one last question, what part of C# am I supposed to research to understand what you told me to add to my script, is it subscribing and events ?
yes events , the playlist I had sent that they butched, has that video iirc
https://learn.unity.com/tutorial/events-uh
there is also the c# resource that goes into more details
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/events/
you might just be the lord and savior himself
I prob shouldn't have been this lazy 💔
(Yesterday i just wasted my time by reading 5 pages of the book, i read like 23 more yet (I was lazy today too)
(C# beginner)
<@&502884371011731486>
@tepid cave not sure what this has to do with programming in Unity or Unity in general. Keep it relevant to the server.
@tepid cave Again, not appropriate for this channel (or server, really). You can DM me about it or send a mod mail if you believe this is important. There's an AI thread on #1157336089242112090. It's a bit odd to suddenly start getting this sort of stuff from an account with no prior interaction with the server.
i cant figure out why the ray isnt pointing from the "barrel"
wdym from the barrel ? it looks like its coming from the barrel
i mean like not facing the same direction as it
its comign out of it then shooting upwards
instead of following the path of the gun
show the the view you are using in game ? cause this looks confusing from this view
apparently they had camera set to ortho
well the game screen wouldnt show the debug ray but here
turn gizmos on in game view
and also show the Move tool in Local mode in scene view for the Pivot
and is the end of the ray at your mouse position?
this is hella confusing , which one has the script ?
you should be putting that script on the pivot of the arm
its at mousePosition - transform.position
because you've assigned its transform.right as the direction
that is not what i asked. i asked if the ray was pointing at your mouse
there is no arm yet it's just a player and a gun haha
yess i see the problem now
the pivot you're showing is at the tip, which one moves the gun capsule thing
its important which direction you scaled it / resting axis
well i removed that pivot point and just assigned the aiming script to the gun itself
with this code
i calculate the direction with the mouseposition
it should but it doesnt really do it it's offset by a bit
here is how I would set it up, Make the capsule the middle, then put a pivot there, then make the gun child of that pivot and move it a bit away from the center capsule (playerbody)
the capusle (gun) in this case is just resized stretched on X but small on Y , without rotation so you see resting pos is (up green) (red right)
GameObject is where you woud put the "gun" script, or better to just put it on the Player itself root, then just make a [SerializeField] private Transform gunPivot
How can I cap a rigidbody's velocity in any direction ? I want the character's speed to quickly ramp up to the max speed instead of instatntly reaching it
if(rb.linearVelocity.magnitude > maxVal)
rb.linearVelocity = vector3.clampMagnitude(rb.linearVelocity,maxVel)```
spoon fed ya the unity part, but the basic answer is usually clamping
actually you probably don't even need the first line just rb.linearVelocity = Vector3.ClampMagnitude(rb.linearVelocity,maxVel)
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Vector3.ClampMagnitude.html
thanks, i'll try implementing that
how can I make it into a specific direction
like clamping it only on the y axis ?
for example
var newVel = rb.linearVelocity
newVel.y = Mathf.Clamp(newVel.y, min, max)
rb.linearVelocity = newVel
you can also use mathf.min (current, max)
idk why it doesnt work🥲 i made the pivot point when i rotate the red rotation axis it works perfectly but it wont follow my mouse correctly the script is attached to the pivot point
Hi, I'm having problems setting the gravity scale in the player data scriptable object, I keep getting an error saying that gravity scale is not a number, what do I do? (I imported a script for my player movement from github for my 2d platformer, and am having issues setting it up)
perhaps show your assignments/calls and where the variables used are coming from
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
whats the site used to share scripts easily? like paste code in and send a link? i cant find it anywhere
nevermind its right there
oops
was WAY scrolled up in chat
Hello guys, I'm currently working on a online game and I created the online system using Photon 2, for now I created 3 scenes: the Character Selector that transits to the Create and Join rooms and then when you joined a room it transits to the Lobby (that I called WaitingRoom)
My ideia is choose your character that is saved on a Hashtable that I called "playerProperties" (the character named: playerProperties["prefab]") and then in the WaitingRoom asign the prefab's name to an already existing static class that has every prefab on it (for ex: PlayerStorage.P1Prefab, PlayerStorage.P2Prefab etc) but this doesn't work on the game. I have 4 spawn points (one for each player) and this spawns for example "PhotonNetwork.Instanciate(PlayerStorage.P1Prefab.name, etc...)" but the game does not spawn that so I think the problem is the WaitingRoom script
A tool for sharing your source code with the world!
nevermind, I figured it out
Hello everyone! I'm working on my first game and have run into some errors. Does anyone know how to fix them?
mm those are internal, not a #💻┃code-beginner question
try restarting the editor, if that doesn't work, try resetting the library, if they still persist try #💻┃unity-talk with that added info
if you set up how i showed it should work esp with the old code.. brw when showing gizmos show with move tool selected
i gave up and fixed it with copilot XD
3 hours on that was too much
ths solution if it interests you
very interesting actually i didnt think of getting the rotation of the end of the barrel to know the current rotation
to determine the bullet's path
For saving/loading (game savedata) do we use
Application.persistentDataPath + "\game.sav"
or something else?
Mostly need it for android and maybe ios builds
Quick question: can I use a 2d collider in a 3D game, where all they'd have to be there for is a raycast to detect them?
yes that is how i normally set my data path then using JsonUtility to save it as a Json file
private static string SkillFilePath = Path.Combine(Application.persistentDataPath, "SkillTreeSkillData.json");
public static void SaveSkill(SkillTreeSkillData Data)
{
string Json = JsonUtility.ToJson(Data, true);
File.WriteAllText(SkillFilePath, Json);
}
ty
well \g wouldn't work
was about to say
for most systems / is used as the separator, just windows that uses \\
yea i switched to / anyway instead of doing \\
there should be a variable for that iirc, i don't remember what it is though
😄
just use game.sav
I think it was Environment something
ok fine noone can complain now
right
🗿
there are a few in there
btw can you even do folders (and subfolders) on android/ios when writing in an app? no clue 🙂
i mean i'm just going to put it at the root so .. just curious
yeah, you can also go in on your phone and edit such files that games save to
at least for android, i dont have an apple to test
I'm not too sure about ios with that 😄
also android neither since google began locking down a bit and I haven't fiddled since a long while with editing app stuff etc on there :S
google did?
i can still edit .sav files from games i've downloaded off the play store though
i'm unsure like i did all the jailbreaking and cfw stuff long ago. i know they made stuff like spoofing root harder. maybe i'm just paranoid lol
well that's good to hear 😛
btw favorite font for coding? @anyone
does vs let you change your font?
jetbraians mono ofc
i've been using the default
i know many people swear by using that but i just don't like it
https://www.jetbrains.com/lp/mono/ best font
how i have to change it to futhark now
try coding with this now
you're not a real programmer if you cant program in wingdings
Aw its soo good
teach me the ways
it's even font on my phone
i mean i guess its kinda good .. triggers nostalgy of minecraft modding 😛
The worst I've seen was coming sans and the minecraft font
yea that's just a troll ...
vs or vsc?
Tools->Options->Environment->Fonts and Colors
visual studio community 2022, the pink one
yeah i got here no clue on how to add my own font to it though
i'm guessing that means you never saw the person with the terraria font
select it there
just install a font by doubleclicking the .ttf .otf or whatever file in windows
ahh
(maybe have to restart vs after installing font)
hmm i like cascadia too ... or maybe just because im used to it
ty i got what i wanted now
when he said minecraft font he meant the readable one not the enchanting table one
nah i got what i actually wanted though thank you
yo can i get some help with somethign
nice!
i need to do a top down ground check, to get the layer that it's on
private void Update()
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up * 5f);
_movement.Set(InputManager.movement.x, InputManager.movement.y);
Debug.Log(hit.collider.gameObject.layer);
rb.linearVelocity = _movement * _moveSpeed;
if (InputManager._changeAction.WasReleasedThisFrame())
{
otherController.enabled = true;
cameraScript.Swap(false);
GetComponent<PlayerMovement>().enabled = false;
}
}
my current code
just to tell me what layer it is
!code especially that last part so people can read your code better
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
you didn't put a space between your links so it was broken. please share code correctly.
#1390346776804069396 for shader issues
Alright thanks
A tool for sharing your source code with the world!
okay, and what is your current issue?
im making a top down game, and i need to check the layer of the object theyre standing on
well to do that you would use some sort of physics query, perhaps a raycast, and from that you can get the layer of the object detected by said query.
im doing a raycast no?
right, so what is your actual problem
Guys, I am having the weirdest problem. "F" doesn't render for whatever reason?!?!?!? lol
im not sure how to do it, its not detecting the layer i want it to
what do you mean by that
i need to detect the layer that the player is standing on. right now, its giving me completely incorrect values of what layer its detecting
how have you determined that it is incorrect
also why do you need the layer? in my experience about 9 times out of 10 someone asking to check that has come up with an XY Problem
im trying to make an ice mechanic like undertale
where when you walk onto it, you slide to the other side without being able to move
does that need to use specific layers instead of just a trigger collider?
remember you are limited to only 32 layers total, reserving a specific layer for something like that means you will then be limited even further for proper usages of layers
ok
love this XY Problem cause it's so true
wdym
read it, wasn't specifically refering to just this case but in general
oh right mb
sorry
well how would i do the collision test?
im new to unity so im not sure sorry
add a trigger collider to your ice layer and let your player react to touching it
you can continue using physics queries for that or you can use physics messages like OnTriggerEnter2D
i would recommend creating a component that goes onto the trigger collider object that tells you what type of material you are on or just handles the entire interaction
the ice script would hold a property thats prefereably an enum
public enum SurfaceType {
Ground = 0,
Ice = 1,
...
}
public class SurfaceView : MonoBehaviour {
[SerializeField] private SurfaceType _surfaceType;
public SurfaceType SurfaceType => _surfaceType;
}
Then you can detect on what surface you are standing on your player like
public void OnTriggerEnter(Collider other) {
if (other.TryGetComponent<SurfaceView>(out var surfaceView)) {
_currentSurface = surfaceView.SurfaceType;
}
}
and depending on currentsurface you can change your player behaviour
ok thanks that helps a lot lol
im coming from unreal engine so I have a rough idea of what things mean but unity handles things super differently
yeah it takes some getting used to things when switching 😄
like for example I wish id be able to see the raycast like you can in ue5. you can just set it to be visible for a certain amount of time
im not really switching its just bc ue5 isn't great with 2d games
Debug.DrawRay

