#💻┃code-beginner
1 messages · Page 653 of 1
If player data is kept elsewhere then it would be safe to let the player object be destroyed and remade later
ok im struggling to understand and use this package. The issue is Meta doccumentation is only in oculus SDK while im working on using Meta XR SDK both are different but provide the same feature and value. i cant use oculus because i dont have the gear that utilize it. Soo im struggling to find the directory name and namespace associated with the directory
it's linked on that page:> https://assetstore.unity.com/packages/tools/integration/meta-voice-sdk-immersive-voice-commands-264555
still not sure what you mean by "directory" though
do you mean "package"?
that's a namespace
nope those are namespaces
not packages
c# basics time i think
packages can define namespaces
pls doo im confused right now
why you asking a non-code question in a code channel? 😄
not a code question. but double click your canvas to focus it, it's likely a screen space overlay so it won't be positioned in world space
using a name space lets you do:
using UnityEngine;
Debug.Log("foo"):
Otherwise you can do UnityEngine.Debug.Log("bar");
or is this question actually about the lighting and not the lack of canvas visible in scene view? 🤔 (even still, it's not a code question)
using Meta.WitAi;
public Wit AppResponder;
so if i write like this ,what does the Wit stand for?
that would be a type. if you don't know what types are, then stop what you are doing and start with the beginner courses pinned in this channel.
oooooo might do that then
You can also just do SetActive(false)
many ways to hide something or restrict what a camera can see
im trying to use Mathf.Lerp to have a npc follow the player in a vector 2 format but im not sure on how id use the time parameter
would i just slowly increase the time by 0.1 until the npc reaches the destination and then reset it to 0?
It's the percentage between the two given values you want it to be
thank you 
it would probably be more appropriate to use MoveTowards rather than Lerp for that
Also, if you do end up using lerp, you should probably do Vector2.Lerp and not the Math one.
hey yall, back again with another code logic question
so I have three scripts:
GameManager, which has references for the monster and player
RoomManager, which has a reference to a Room object - this generates a random room for the player and monster to teleport to
Room, which stores 3 transform values - 2 for the player and monster's teleport locations
currently, RoomManager has the Teleport() function, which teleports the player and the monster between rooms, however it needs a reference to the player and monster (which it doesn't right now)
I had an idea of maybe moving this function to GameManager, since it'd probably make more sense there - however then i'd need to reference the Room object from RoomManager, which I feel makes the object call quite verbose
This is the script I have in RoomManager right now, note that player and monster aren't referenced, so this is non-functional at the moment
public void Teleport(GameObject player, GameObject monster)
{
SaveOffset(player, monster);
playerRb.MovePosition(currentRoom.playerSpawn.position);
float distance = offset.magnitude;
float monsterSpeed = monster.GetComponent<Monster>().speed;
float waitTime = distance / monsterSpeed;
StartCoroutine(DelayingMonsterTeleport(monster, currentRoom.monsterSpawn.position, waitTime));
}
specifically at the Coroutine with currentRoom, I think the call would extend to something like RoomManager.instance.currentRoom.monsterSpawn.position
would there be a better approach than this? Perhaps using observer pattern again?
what causes the teleportation to happen
Teleportation is currently called from the RoomManager script
the flow goes like:
player enters a door -> gamemanager says "ok, roommanager can you teleport them, and then generate a room for them as well" -> roommanager generates a room, calls teleport
public void TriggerEvent(Type trigger)
{
switch (trigger)
{
case Type.Die:
monster.KillPlayer();
player.Die();
break;
case Type.StartLevel:
monster.StartMonster();
// Roommanager.instance.generateRoom();
//generateRoom(false);
break;
case Type.NextLevel:
//generateRoom(true);
break;
case Type.PreviousLevel:
//generateRoom(false);
break;
case Type.ResetLevel:
player.ResetPlayer();
//restartRoom();
break;
case Type.WinGame:
SceneManager.LoadScene("MainMenu");
break;
}
This is part of the gamemanager
I'd be okay with referencing the player and monster again, just to keep Teleport in RoomManager, but just wanted to ask if there's probably a better way to do this
A tool for sharing your source code with the world!
the conditions arent getting triggered for some reason
How about logging both values and the distance between them, and seeing if they're what you expect?
i just did that actually
looks like the coroutine is just not getting triggered for some reason
wait no it is
why did you put a constant value for third param?
i thought it was the max distance it could stray away from the position it was going to
also ur not assigning that v3 movetowards return value to anything
oh i see
im guessing i misunderstood its role?
I think max delta is fine to be constant actually but ig needs time.deltaTime to keep it so
this is what i ended up with but it doesnt seem to be working
https://paste.mod.gg/pquanijzcqpz/0
A tool for sharing your source code with the world!
did Debug.Log print ?
yes
how many times? multiple times?
I can't tell how many times .. 0.4 seems wrong as start tho no?
once, but i think i know what i did wrong now
i start the coroutine using a script in the copy of the text box
and that gets killed
huh this moving code is in a textbox script?
btw you probably want some type of a star here or third party 2d navmesh. this will take the most direct route ignoring walls or water
the moving code is in the npc manager script but i am starting the coroutine in a textbox script
is there a manual for this I can look at? (this is my second game on unity)
There are pre-made solutions. Like the a* project by aaron berg or https://github.com/h8man/NavMeshPlus
Unity NavMesh 2D Pathfinding. Contribute to h8man/NavMeshPlus development by creating an account on GitHub.
Does anyone have a good guide on making hud elements? I just want to see a number while moving?
i dont know whether im overdoing this, or got some unnecessary steps
currently i have a setup to initialize my "player" gameobject using SO, my game is pure idle + farming + social game, as i said
so theres no battles, my characters dont even need "attributes"
its guaranteed that 1 character will only have 1 dedicated animation set
and because each characters will have different hierachy like these + skinned mesh renderer
i will need to make prefab to each of them, otherwise its too difficult to use SO to swap/populate every components/materials/textures
my question is, do SO really needed here
i already needed a prefab for each of the characters anyway.....
one of the possible benefits, i think its multiplayer, if i stored prefab under a SO
because in my game, im allowing multiple players to choose same characters
i think its still usable
i will have different skin(avatar/forms) of characters, which is swapping out meshes , and maybe animation sets
is it bad practice to have public static bool for player states such as inAttackAnimation and isRolling even if its for a player script and there is only one player?
so at the end it might be
- ID
- original character prefab
- List: possible skins
- List: possible animation controllers```
Why do you want them to be static?
easier to implement multiple states and easier to modify
tmp(text mesh pro) is the absolute king when working with ui
Hello again yall 😅
why would that be different from nonstatic fields?
https://nohello.net , just open with your question
I disagree with this sentiment
it just causes more noise, you can always put pleasantries in your actual question message
Seeing some weird behavior from my code...
Vector3 wallNormal = wallRight ? rightWallHit.normal : leftWallHit.normal; Vector3 wallForward = Vector3.Cross(wallNormal, transform.up); rb.AddForce(wallForward * wallRunForce, ForceMode.Force); Debug.DrawRay(pm.transform.position, wallForward * 500, Color.green, 10f);
the wallForward vector works for applying force to my character, but it is not working for the draw ray
wdym by "not working"? is it not showing up, or is it showing up in the wrong place?
I'm hoping to use this vector to rotate my character in the direction of the wall forward, but that's not working either.
Does not show up at all, character doesn't rotate either when I do this
playerObject.forward = Vector3.Slerp(playerObject.forward, wallForward, Time.deltaTime * 10f);
this in Update?
it's 3 levels down in nested functions but the top level function is running in update
scriptname.property for all states to set/get
i feel like you'd be better off with a singleton for that
have you tried logging all the relevant values?
ah its returning 0,0,0
Forgot to say thanks. This guide helped a lot
!collab, and don't crosspost
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
Guys I tried downloading visual studio 6 but Microsoft Visual Studio community 2022 is giving a error "Download Failed: Validation Failed"
I tried searching online and it said to run unity with administrator but it didn't work. Also tried installing manually but it won't download and stays at 0-kbs
not a code issue, #💻┃unity-talk
u guys think it is forgivable to do such thing in a scriptable object🤣
[field: SerializeField] public List<int> VariantIndex { get; private set; }
[field: SerializeField] public List<Material> OtherMaterial { get; private set; }
//use this instead of the key/value list
public Dictionary<int, Material> MaterialVariations()
{
Dictionary<int , Material> temp = new();
for (int i = 0; i < VariantIndex.Count; i++)
{
temp.Add(VariantIndex[i],OtherMaterial[i]);
}
return temp;
}```
it worked tho...... welp desperate moments with desperate measures
you should give the dictionary a start capacity as you know how big it will be
and there is no guarantee this wont fail on creation if you put duplicate "keys"
anyway plenty of "serializable dictionaries" exist online
int count = VariantIndex.Count < OtherMaterial.Count ? VariantIndex.Count : OtherMaterial.Count;
Dictionary<int, Material> temp = new Dictionary<int, Material>(count);
for (int i = 0; i < count; i++)
temp.Add(VariantIndex[i],OtherMaterial[i]);
return temp;```
ty i will look at this first
you should at least use a list of structs to guarantee that keys and values match up (and so they're beside each other)
or just go for the serializeddictionary plugin
what should i do if i want my character to face a certain direction when it spawns on a location>??
i rotate its position in the scene but it keeps facing north than what i put him in the scene
Ive wrote this code to make the camera follow the player but it does not follow the player and the camera falls indefinetly on the z axis
well how are you doing the spawning? do the rotation there, rather than in the scene
ty guys 👍 at the end i made up my minds and use a plugin lol
im not doing any tests or exams in class, im making games, so i gonna use what asset stores already have
you're setting targetPosition as your own position instead of target's position
also for future reference, !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/, https://scriptbin.xyz/
📃 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 do i fix that
use target's position instead of your own position
yeah it's really straightforward
then check out beginner c# resources in 
ohhh thank you
where can I learn through videos because i strugle to learn through reading
don't have any recommendations, in general text articles will be easier to skim through, backtrack, or search content
Can I make an int property have a range of it only having numbers from 0-8 or do I need an enum for that? Cause feels kinda silly using an enum for actual numbers lol
You can put the range attribute on its backing field if you mean for the inspector. if you want to clamp it to that range in the actual code, then just clamp it in the setter
It would be better if it always remains within the range, since it's basically an id than can never go beyond 8, but I guess the range attribute would do
then clamp it in the setter like i said
but use the range attribute too so that the backing field is restricted to that range for the inspector
if clamping via the setter, I would personally log a warning if an attempt to set it outside of that range occurs
Shouldn't be the case that I try to change it in runtime, I think
sure, but just in case you do the warning would be useful
You still need to clamp it because the Range attribute only affects the inspector value, not when set in code . . .
It should be never set in code, I am just REALLY having a headache on how to implement what I am doing, since you have 8 commands (with ids 1-8). These are on a list that is never touched, but then I have another list for active commands, player can add a command to this list, and it would add the lowest id number avaliable to the list, but they can also remove ANY at any time from the list, basically letting to an unorganized list where you could have like 1, 2, 4, 3, 5, 6 and the items having a different a Index on the list than id is fucking my mind lol
at this point it is really starting to sound like an enum might be more appropriate. if these "ids" are supposed to represent specific commands then it really should be an enum. that's what enums are, ints with labels
i know that this isnt the right channel but i cant find one fitting for my question, would it be possible to change the tilling value for all new materials? so instead of 1 its 0.3
so when a new material is created in any way it has 0.3 by 0.3 on by default
this is a code channel.
#🔎┃find-a-channel
Why doesnt it work? here is the code:
public class GameManager : MonoBehaviour
{
public int money;
[SerializeField] private AudioSource audioSource;
private Animator animator;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void Click()
{
money++;
animator.Play("SlimeClickAnimation");
Debug.Log("Clicked");
if (audioSource.isPlaying == false)
{
audioSource.Play();
}
}
}
have you confirmed the button actually works?
wdym
i mean exactly what i said
it should work
have you done literally anything at all to confirm it does
Is the button responding to the mouse, like changing colors on click or anything
no it doesnt, but why? it should work
Do you have an event system in your scene
well with your current setup it wouldn't change colors on click because it has no target graphic
no
Ah, right, good call. That would also mean nothing that's a raycast target either
should i make like collider 2d
So, add one, and set the target graphic for your button to the image you want to actually click on
how can i add?
oh its component
ok i added
Create -> UI -> Event system
It allows you to click on UI elements
but it still doesnt work
Did you do the second step
but normally we can click
And assign a target graphic to the button
Not without an event system you cant
i did
It gets created when you first create any UI object, so don't delete it
oh
your button is also not on a canvas
Yes now you have an event system. Did you set a target graphic in the button yet
oh yeah u are right
i sent a photo
i guess i did
Where? The only screenshot of your button shows it not set
wait why is the event system component attached to the button?
there is just so much wrong here
and none of it is code related
where should i attach it then?
you should do what digi suggested and create it separately from the Create menu
It should be an object that gets created when you first add any UI elements. But also since you don't seem to have made any that's why you don't have it. They would also come with a canvas
when i add that, it automaticly adds the event system to the slimeclick gameobject
also, do i have to create a Canvas first of all?
No, it doesn't
it does
Did you remove the ones from the object before attempting to add a new one?
ok, i deleted the event system from the game object which is called SlimeClick
now it does
Assuming you want to use any UI elements at all, they must be on a canvas yes
You can only have one event system. It won't create one if it already exists in the scene
Probably, maybe I should label them with leters
or you use descriptive names in an enum instead of cryptic letters and numbers
There is nothing to be descriptive there, they can be many different things
The idea is that the player can make these do and look whatever they want to, so... it's not like I can give them a name that makes sense
in that case you need to actually be descriptive about wtf you are trying to accomplish so that a proper solution can be suggested because at this point it is impossible to tell what the actual fuck you are doing since you refuse to actually describe it
Well, picture this: right side UI shows a list of commands, you can add up to 8, these commands have different things you can do and you are meant to be able to change how they look (picture them sorta like WoW macros). You can add them 1 by 1 (it would automatically add the lowest id that is not yet active as the last one on the list and UI). You can remove any of them at any time. This right UI is the part where you configure what these do, but you actually have to use them on the bottom UI.
Bottom UI would have to update to the order of the right UI, so if you have a list of Ids 2, 6, 4 on the right, the buttons showing on the bottom should be those corresponding to those commands and be on that same order. The Id reference must hold what the heck those specific commands are meant to do.
And to make this even more confusing, I am also adding like extra funcions to the commands that basically is a list of commands inside a command that would be executed on that order alongside it (they use the same script, but are tagged as id 0, so you can know they are not the main ones). So for example if the command says "Move X to Y", you can have 2 functions inside of it also saying "Move Y to Z" and "Attack Z" and it would be executed on that order with a single buttom press.
That's the idea, how to make that work is still to solve for me lol
Are you doing for runtime purpose or edition purpose ?
it sounds like all you need is two arrays, you don't need this ambiguous "id" variable. when something changes in the "right side UI" you just update both arrays
Runtime
Aren't arrays unordered?
what? no, arrays are fixed size and are "ordered" in the way you specify since you put things into specific indices
Why does the animation just play 1 time?
public void Click()
{
money++;
animator.Play("SlimeClickAnimation");
if (audioSource.isPlaying == false)
{
audioSource.Play();
}
}
Is this a bad practice?
// "piece" script
void LateUpdate()
{
gm.gameGrid.gameHexes[currentPosition].setPieceOnHex(this);
}
// "tile" script
void Update()
{
pieceOnHex = null;
}
I want to track which "pieces" are on which tiles. This way each of my tiles update instantly to "null" whenever there are no piece on it.
But somehow this feels a bit...hacky?
You could implement a MVVM layer to bind your data reducing the needs to manually keep your UI refreshed. (Making it trivial to sync multiple UI as well)
hoiw many times do you expect it to play?
yes this is a bad practice
when i click
Set it when the piece goes on the hex. and remove it when it is removed. No need to do something every frame.
Start debugging your code. Add Debug.Log there to make sure the code is running when you expect.
A what?????
its running, the slime does increase
But I wonder how can I track that. I don't want to use any physics based solution like OnCollisionExit, etc.
Why would you need physics?
You would do it when you're setting currentPosition
what is "it" in this context
why does what say what is null?
it is the debug console
That's... not really saying much, just giving it a presumptuous name...
if only there were links in the search results that explain the architecture and how it works
you're looking at the wrong object
as the log says, it's the object called "Idle" where it's not assigned.
so make it look in children?
oh
i'm just curious why you put the gameobject's name in your log if you didn't plan on actually looking at that part of the log
I wont teach you what it is, I simply named something that could be really useful so you can interest yourself to it.
i didnt realize it cus i was working on gettting the spider working not the dummy
its a soft lock system that id s targets
As far as I have read this is basically what I am already trying to do?
It's being also set up in Update() as
currentPosition = gm.gameGrid.gameGrid.WorldToCell(transform.position);
Not sure how can I do that without running that every frame
Like it's just a type of workflow
im not much of a coder just trying to get this working for my class
there is no reason to do that in update. Where do you change the position?
Currently nowhere, I just tested it by manually dragging the gameobjects
You should basically do this:
public void SetPosition(Vector3Int newPosition) {
var oldPosition = currentPosition;
gm.gameGrid.gameHexes[oldPosition].setPieceOnHex(null); // set old position to null - we're removing ourselves
currentPosition = newPosition;
gm.gameGrid.gameHexes[currentPosition].setPieceOnHex(this); // assign ourselves to the new position
// move physically
transform.position = gm.gameGrid.gameGrid.CellToWorld(transform.newPosition);
}```
Then you only move by calling SetPosition
now everything works
Ah that should work, ty
hello, i need help with this project. im making a plinko game rn and i want an animation to play when the ball hits a peg. currently the peg and animation arent connected to each other and idk how to go about this
what kind of animation? On what object?
Uhhh Is this like a bug or something? 🤔
i tried both .text = and .SetText restarted unity.. same result
i mean if not in your own code, maybe the canvas isn't rerendering or smth? idk, try #📲┃ui-ux
also what is going on with that null ref on clicking the text lol i have no idea
ohh okay I will try there ig.. thought something is going on with code cause my Connected text works fine
was thinking also might had to do with something with Events / Async
🤔 the repeated clicking on the text input xxxx was trying to resubmit, right? what if you disable and reenable it?
no there is no logic on the clicking thats why its sus that is doing that.. the only interaction is pressing enter in the TMP Input field that sumbits the text to a server, then server responds fine as seen in the inspector but the canvas wont react until I touch the inspector and modify the text again..
here is code for context
private string messages;
void OnEnable()
{
inputText.onSubmit.AddListener(InputTextSubmit);
gameHubController.OnConnected += OnConnected;
gameHubController.OnMessageReceive += OnMessageReceive;
connectedText.text = "disconnected";
}
private void OnMessageReceive(string msg)
{
messages += msg;
messages += Environment.NewLine;
messagesText.SetText(messages);
}```
i mean clicking in the inspector
was it just clicking or did you press enter?
oh I did not press enter at all
oh
https://discussions.unity.com/t/textmeshpro-settext-method-doesnt-set-text-properly/779079/4
anyways seems like .text = is the.. "correct" way?
I tried both
I used SetText cause .text wasn't working thinking maybe was event issue but no, it works fine for the connectedText
maybe need to mark something dirty
when is OnMessageReceived called? is it perhaps not on the main thread?
yeah thats what I was thinking tbh..I am using async for that
Simple question. Im trying to get input for My game. Input needs to switch camera 1 to 2 after pressing a certain key. Whats The simplest code for that
protected async Awaitable InitHubAsync()
{
HubConnect();
// Handle incoming messages
hubConnection.On
<string, string>("ReceiveMessage", (user, message) =>
{
var mesg = $"user: {user} \n message: {message}";
Debug.Log(mesg);
OnMessageReceive?.Invoke(mesg);
});
try
{
await hubConnection.StartAsync();
isConnected = true;
OnConnected?.Invoke(isConnected);
Debug.Log("Connected..");
}
catch (Exception ex)
{
Debug.Log($"Connection error: {ex.Message}");
}
}```
seems like you can check for that
https://stackoverflow.com/questions/26452609/find-out-if-im-on-the-unity-thread
idk about async stuff, can't help with that, sorry lol
This is the only thing thats different so I'm gonna take your suggestion this is probably to do with threads, its weird cause it told me that Debug.Log can't be called on non-main thread..until i used Awaitable (it used to be Task)
if the thread thing turns out to be the issue, you could probably just move messagesText = messages; to Update
CinemachineCamera camA;
CinemachineCamera camB;
bool isB;
private void Update() {
if (Keyboard.current.spaceKey.wasPressedThisFrame){
isB = !isB
camB.Priority = isB ? 1 : 0;
camA.Priority = isB ? 0 : 1;
}
}
could make it "simpler"
CinemachineCamera camA;
CinemachineCamera camB;
private void Update() {
if (Keyboard.current.spaceKey.wasPressedThisFrame){
camA.Priority = camA.Priority == 0 ? 1 : 0;
camB.Priority = camA.Priority == 0 ? 1 : 0;
}
}
Is that simpliest?
probably not
I mean for me it seems like a simple as frick thing to do
simplest is meaningless, use the one you understand
but really "simple" can mean a lot of things yeah
also this is just the code, it makes assumptions about the scene config
Yeah i know, for me The code im thinking would Be just like "If you press this The camera changes and If you press it again The camera would change to original"
But im just a newbie so : D
i think the correct pattern here is to capture the notion of this toggle state in a variable and apply it to whatever you want that does the switching
any trickery that eliminates this dedicated variable is, in my book, less simple, harder to understand and more prone to breaking.
so you nudged me in the right direction it seems
my personal definition of "simple" is short
```cs
CinemachineCamera a,b;void Update(){if(Keyboard.current.spaceKey.wasPressedThisFrame)b.Priority=1-(a.Priority=1-a.Priority);}
a code golfers definition
I have this game that I'm making for an assignment due tonight (i procrastinated too hard whoops) - Its a top down 2D tile-based movement game where you can push around some crates, activate switches with those crates to open gates, step on portals and teleport to them later, and pick up items which increase the total moves you have per level. I have all of those things except the crates working properly and i would hugely appreciate some help with it. Right now, I have them being pushed just fine but I would like to only allow one to be pushed at a time, which I am seriously struggling to implement. I have a really screwed up movement system but I dont have time to make a better one and I'm kind of freaking out about it
gotta show setup + !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/, https://scriptbin.xyz/
📃 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.
for eample, the walls, rather than having physical colliders, have triggers which interact with the player's hitbox which is + shaped. These triggers prevent the player from making a move into a wall. For the crates, I move them around using normal colliders but am trying to make them do basically the same thing as the walls. To try and achieve this, I've made 4 child objects for each crate which also sit around it in a + shape so it knows which direction things are in, and i'm trying to make it so that when it triggers against another crate AND the player object on the opposite side it prevents the player from moving towards the crate and therefore pushing more than one
its jacked up
will do
there's the player movement script
thats the main crate controller
and thats an example of one of the crate children (this one is on the right side, so theres 3 more for the 3 other sides)
its a really messed up setup but like I said I do not feel like I have the time to make a better one since I still have to do level design and some menus
could you make video of the problem?
Also what exactly is the reason to make walls triggers
I made the walls triggers because I'm using a tile based movement system so i didnt want the player to be able to move towards them and then be off-center
in hindsight i understand this was dumb but i dont have the time to fix it
off center ?
yeah it's a tile based movement thing so I dont want the player to be off of the center of the tile
I dont see how trigger vs not would change any of that
the trigger is preventing the player from making a move towards the wall in the first place rather than having them bounce off the wall and then not be in the center of the tile
ohh rigidbody collision you mean
yeah
in any case the walls work fine so janky system or not im not worried about that
but now you have the same problem to solve with moving boxes
what I'm trying to do is make it so when triggers attached to the crates detect a crate on one side of it and a player on the other side, it basically tells the player that theres a wall there so it cant move into that tile
essentially preventing the player from making a move to push multiple crates
when its just a single crate the pushing mechanics work fine and the crates also detect walls just fine
this is literally my second time making anything in unity so everything is like weird LMAO im sorry
might need to look into using the other box to push the box infront of it
hey guys, do I need to run the AddEventListener only once if I want some functino to be run when some event happens?
AddListener is used to subscribe / listen to an event
nvm I just realised something, oops
hey, im making a player movement script and for some reason whenever i start jumping while moving around, if i stop pressing the WASD keys but still hold the jump key, my rigidbody continues to move in the direction i was going initially, kinda like a bunny hop. does anyone know why this might happen? this is the code that handles jumping. the HandleJumping method is being called in FixedUpdate
private void Awake()
{
input = new InputActions();
input.Player.Jump.performed += ctx => isJumping = true;
input.Player.Jump.canceled += ctx => isJumping = false;
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true;
ResetJump();
}
private void HandleJumping()
{
if (isJumping && readyToJump && grounded)
{
readyToJump = false;
rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
Invoke(nameof(ResetJump), jumpCooldown);
}
}
private void ResetJump()
{
readyToJump = true;
}
bunny hop implies to me you keep jumping, are you also constantly jumping ?
the best way for you to solve it is to breakdown the steps you will need to verify and debug it
examples, which values are what you expect them to be vs not
only that first line is actually in the if statement's scope
because the rest are not in the {}
Wait really?
yes, this is c# where white space does not denote scope
I'm new to c
without {} if statement only counts whats directly after it
it's also not c, it's c#
as nav has pointed out twice now you need curly brackets
yes, im constantly jumping. all of the values seem to be fine and my ground check works as it should
Also working on a flickering flashlight script, I know i'll need a loop, I'm using an IEumerator currently, Is this a bad way to add a delay?
this obviously isnt a loop yet
not a bad way but overkill
this will only happen once btw
I did something like this on a static light in my scene is this better?
Time.deltaTime usually works fine
tyty 🙂
hm define "fine" lol cause the end result seems anything but that..
also would try testing it in a build just incase its not an editor thing
back when , I recall un focusing the game window by accident would cause that key not to release
well my move input vector values are 0, 0 so the keys cant still be pressed
whenever i stop pressing wasd but keep holding space, the velocity remains the same but slowly goes to 0 on the x and z values
do you move using AddForce or .velocity ?
AddForce
btw I found a script I made a while ago a more "randomized" pattern using intensity, if you're interested into that as well
private IEnumerator Flicker()
{
while (true)
{
for (int i = 0; i < lights.Length; i++)
{
float flicker = Mathf.PerlinNoise(Time.time * flickerSpeed, 0);
float intensity = Mathf.Lerp(minIntensity, maxIntensity, flicker);
lightMesh.material = intensity < maxIntensity / 2 ? lightOffMa : lightOnMa
lights[i].intensity = intensity;
}
yield return null;
}
}```
made a few years back so its not cleanest but might come in handy
(you can probably ignore the material part unless you want to do that as well to "swap textures"
but thats why it keeps moving no? (moving slowing cause of deceleration)
https://paste.mod.gg/lzgjeirrszsx/0 APOLOGIES FOR MY MESSY ASS CODE
so basically, i have a fish swimming down a stream, and it is supposed to fall when it gets to a certain point (line 76), i have tried what i think is everything at this point and ive even used debugs, and my code should be running but it isnt. could anyone help?
A tool for sharing your source code with the world!
yeah, it makes sense now that i think of it, but how could i stop this deceleration and just stop the player instantly when they stop moving while jumping?
its probably another copy of script somewhere with all those unassigned
Ooh i'll have a dig
you can search the hierarchy with t:DoorLogic
Yep I found it instantly! Thanks, That's a nice thing to have learnt and I guess happens alot more than people expect
its pretty common yea lol
Also forgetting to hit 'stop' and editing while in playmode has tripped me up a few times now
i think i had a similar thing happen to me a day or two ago lmao
You could prob opt for using .velocity instead of addforce?
helps to have a PlayMode Tint color
should've been default tbh
I make my tint more red for that reason
btw, ive been working on this for like 2 hours and i cant find the problem @. @
its pretty messy to scan through all this, are you checking the logs?
..use debugger is probably less of a pain to go back n forth adding lines instead of just breakpoints
yeah, and basically what the logs are telling me is that the code should be running, im getting the debug but its not moving any differently
always verify the values we expect are actually the values that are happenig
i did that too but i can check again rq
dont just log the "code should be running" log specific things
wdym?
just cause the function might be running doesn't mean the values are what you expect them to be
thats a good point
thats why youd normally log whats in that function etc.
string myName= "bob" ;
void MyName(){
Debug.Log(myName)
vs
Debug.Log("its running")
i've tried that when first deciding of how to move the player but i didnt really like that it starts and stops moving instantly, i like the way it slowly starts moving and slows down with AddForce
i mean technically you can code acceleration / deceleration logic yourself too
its fairly easy esp with Animation Curves / MoveTowards and such
Am i allowed to share a janky preview of how my games coming along here?
best for #1180170818983051344
Sweet thanks!
so the y value is in fact what im seeing, and its j ust not going up or down, even though im telling it to change the line before the debug
When you dont know how to UV map properly or use the correct shader so you just place walls connected at this size everywhere (pain)
Try a triplanar shader/material
I remember rea
Doesn't need UVs
which line is that? you logged the actual Y value as well ?
I was about to type that
yeah, 77 & 78
I looked online but wasnt sure what/where to get one or how to install it
What renderpipeline are you on? The default Lit shader probably has it. Set UV mode to triplanar in the material settings
I'm on URP/lit
you did Debug.Log( $"y value {y} " ); ?
i feel like that would a too complicated fix for this, i guess i'll have to do some more research and find out what the problem is and just code acceleration and deceleration myself if i dont find anything helpful
just debug.log(y)
and it was moving ?
on each individual material?
so many magic numbers here my brain is exploding lol
would also log Fish.transform.position and see whats happening there
eg like before 77 and 78
I don't really know URP, but looks like it doesn't have it actually
https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@12.0/manual/lit-shader.html
Yeah I dont think it does, I did look a little last night
You gonna have to 
im so mad at myself i found the problem
i wasnt updating "num" at the right spot
I'm almost done with my first game so i'll just leave it how I have it currently, It's a pain to work with but i'll look into triplanar next game lol
that simple replacement took two hours
hey at least you narrowed the problem
it be like that fr
Can I make an UI element no be part of the EvemtSystem?
Cause entities have a canvas in world space over them but they don't ever need to be interacted
Untick the raycast target on the graphic objects
when i try and run some code for the camera to follow i get hit with the same error can i get help with what it means? (ill get it real quick)
where my cursor is at is line 21 sorry i forgot to screenshot the numbers too
you've configured your project to use the new input system, but you're trying to use the old input system
ohhh okay, how would i switch to the new input system?
there's a lot of ways to do that, try googling for some
okay thanks
I made a (possibly) simple menu with buttons based on races and classes of a game I like that sets stats based on race. I can get the race to set the class availability list and make stats appear (although someone said my method seems too hardcoded???)
How can I get it so its like “if race/class combo then these religions are available and these stats are adjusted by class”
Im sorry if I cant explain better but I really am that newbie at code
I made this almost a year ago but I had some real life and so its been on back burner and now it feels like I don’t even remember how I made this
And Ive tried to understand code but its like impossible to clikc
made a png with some text for my horror game in photoshop dragged it in as a sprite renderer (i assume thats the correct way) and it kinda.. glows from far away?
Is that due to the shader?
glow sounds like its from Bloom / Post Processing
Is my question too complex? Im sorry if Im not wording it well
not sure what exactly you're asking?
sounds like a simple math thing
Yea but when I try to do “add total” it doesnt work. I can try to look at the code when I get home but again Im not sure how to explain
well without us looking at the code to precisely see what you're doing we can't offer much
Hello guys,i am beginner and learning from Unity pathway (https://learn.unity.com/pathway/junior-programmer/unit/sound-and-effects/tutorial/lesson-3-3-don-t-just-stand-there-1?version=6).
I have problem with animation when player falls down and its change from falling (Death_01) to laying on ground (Dead_01), player wil start runing again. Thats mean that fell animation wont continue and will restart to running. I follow all instructions from tutorials/pathway.
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
Making a horror game is slowly making me feel insane lmao
Archive of freely downloadable fonts. Browse by alphabetical listing, by style, by author or by popularity.
you have to show the code and the setup is the same, otherwise we can't tell much from this only
Here is screenshot that animation Dead_01 is enabled, but player started runing after adnimation time set to "full". I will show you code of player animation.
which part of the lesson shows how to setup . cause honestly dont feel like going through the entire thing lol
using UnityEngine;
public class PlayerController : MonoBehaviour
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
private Rigidbody playerRB;
public float jumpForce = 10f;
public float gravityModifier = 2f;
public bool isOnGround = true;
public bool gameOver = false;
private Animator playerAnimator;
void Start()
{
playerRB = GetComponent<Rigidbody>();
Physics.gravity *= gravityModifier;
playerAnimator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && isOnGround && !gameOver)
{
playerRB.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
isOnGround = false;
playerAnimator.SetTrigger("Jump_trig");
}
}
private void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.CompareTag("Ground"))
{
isOnGround = true;
} else if(collision.gameObject.CompareTag("Obstacle"))
{
gameOver = true;
Debug.Log("Game Over!");
playerAnimator.SetBool("Death_b", true);
playerAnimator.SetInteger("DeathType_int", 1);
}
}
}
``` Here is entire PlayerControll.cs script.
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
what about the transitions?
the inspector for them
Alive to Death1 ?
so after death is starts running again, when exactly?
Yes, when Death_1 change to Dead_1 it normal, but after Dead_1 ends it start running again
Dead_01 is like this
An player still runing
are you sure the correct animation ?
so many layers on that animator it throws me off
I followed instuctions from video, only if i miss something somewhere. But i am sure that i have same and i chechek couple times
Here is how it looks when i run.
Only way to try fix this is by replacing animation with new one, the original one and check again
check the same thing but with the BODY layer selected...but to me also looks like the Dead01 has wrong animation clip
idk how to fix this, the error message is "Cannot implicitly convert type 'UnityEngine.Vector2' to 'float' " and rb is a RigidBody2D
could someone help me here please?
movespeed is a float
angularVelocity is rotation not movement
Here is with BODY selected.
https://docs.unity3d.com/ScriptReference/Rigidbody2D-angularVelocity.html as the error is telling you, angularVelocity is the float. you cant convert the vector you're trying to assign to a float
oh ok thanks lol
linearVelocity is what ur looking for. Also you should remove Time.deltaTime from the calculation for rigidbody
I meant to use rp.velocity
ok
thanks
I'll make those changes
Also Running animation that is deafult is still runing behing even when falling animation is running
And its never stops
wdym by this?
when falling animation starts, Run_static is still working.
I reseted all animations settings and still didn't fix
This is what i talk about.
where is supposed go from there ? did you check the transition is correct
From running to jumping when press spacebar, that is working fine, but main problem is with Dead_01 animation. Run_static is deafult state
im back again, i think my game just needs someones expert eyes because whatever i do/change regardless if I did it or chatgpt does it (which i cannot look at chatgpt rn hate it), doesnt seem to be playable when putting it into like itch.io or anything free 😭 (but playable when i run it ofc) if anyone’s free and can help me, ill send ss and everything your way… i just seriously need help
so now im home this is the kind of code im using currently for the following as i showed above https://cdn.discordapp.com/attachments/831230543227519047/1244506529965543524/My_project_-_Char_Create_-_Windows_Mac_Linux_-_Unity_2022.3.12f1__DX12__2024-05-26_23-11-11.mp4?ex=68164346&is=6814f1c6&hm=ad975dd903e8f8314496f37b3873d99f81c849050a7a658722b41c3916b0bbf9&
what i cant do is make the class side button disable religions or adjust the base stats based on the selected combination
@rich adder sorry for tag. Thank you for helping and i am sorry that i waste your time. I fixed the problem by reinstalling all animations.
i also tried to do a less 'hardcoded" way of setting stats but... doesnt work
does anyone know a good place to learn code along with the unity learning hub?
google has failed me this time unfortunately
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
The unity manual ranks second for me
With youtube coming in last since most people just copy and paste and not learn what a certain line of code
ye, when i use youtube tho i usually break the code im given down and use little comments to say what they do
but ye have to do the coding to learn the coding :<
im slowly learning my inputs now tho
Another tip is to look at the unity manual for the lines of code used
Slows you down a lot at first but helps later down the line
theres a unity manual?
alr im downloading it rn
thanks tho i did not know that
Ur getting it from the official site right?
You don't need to download it. It's available online
I can't get away with an override like this in interfaces right
public interface SubInterface
{
public abstract SubBehaviour Get();
}
public interface SubInterface<T> : SubInterface where T : SubBehaviour
{
public override SubBehaviour Get() => GetBehaviour();
public abstract T GetBehaviour();
}
yes
i know Im very unknowledged on this but any help understandin
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
But also why not make a int list and store the values in there?
I can try. Never done it before
:[
Fair enough
I need help on my code
You need to start by configuring your !ide
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
• :question: Other/None
Then once you can see your errors and have autocomplete you can match every brace up appropriately
it says "No problems found, and plus, i configured my visual studio to unity
its not configured, we can tell
if it was configured what you saw in unity console would show in IDE
dam
well, ok, i will configure my ide now...
i read the page and i think my ide is configured
this is like the last step, there are several others before it
oh
if its not underlining red in the editor then its not configured
i checked for updates and visual studio is up to date
sorry to populate this with another collision troubleshooting issue but I'm trying to learn the new input system and got lost on how to properly code my setup. so i discovered rule tiles and wanted to make a system like this, i'm going for pixel perfect movement but the players box collider keeps passing though walls.
player controller code https://paste.mod.gg/qgalmowxmcqx/0
A tool for sharing your source code with the world!
you have an rb but you aren't using it. rb controls the transform, so you shouldn't control the transform yourself - that leads to conflicts
use rb.addforce or velocity to let the rb respect collisions
so teh Physics2D.OverlapCircle is no good now?
well that kind of check could probably let you clip through corners in an edge case (or perhaps a corner case 😆)
but yeah if you have an rb why not use that
its the box collider im interested in using, and changing it to the the boxes transform didn't change anything so i guess its in the colCheck....?
also you aren't giving any layermask to the overlap circle so that could hit yourself
no clue what you mean by any of that
my box collider keeps passing though walls
what did you mean by "changing it to the boxes transform"?
you said i shoudlnt control teh trasnform myself, so i updated it
if the box collider is on the same component then it's the same transform
A tool for sharing your source code with the world!
so then its a problem with the colCheck function?
you don't need the colCheck function
then how do i check for walls?
you don't have to
the rb will detect and respect collisions on its own if you use velocity or addforce
but im going for pixel perfect movement, like they'll stop on the center of a tile when i release the key?
that isn't pixel perfect
that's moving on a grid
are you having diagonal movement with this?
ok so you don't want physics-based movement, why use rbs then lol
mostly i jsut want the box collider?
then just use that
it passes though my walls
that isn't solved by arbitrarily adding an rb and then ignoring its existence
fine ill remove the rb
btw what's with putting it in FixedUpdate, why not just put that in the playerinput message
nope, still passes though twalls
because if i did that i would have to press the button EVERY tile
this also feels suspicious, but we can get back to this later
hmm i might just be forgetting how value types work lol. anyways could still be in Update, since it's about input
yeah of course it would be, you haven't changed anything meaningful at this point
do your walls have colliders?
yes
ok so start debugging - try logging out what the overlap circle returns, try logging out that position and see if that's right
im logging the dir vector but i dont know how thats helpful
its true on floor, false on walls, except when i go up
if i raise the radius on the overlap circle i cant move down
make sure you have the right physics shape for your walls
i do
Why are you doing all this complicated input logic instead of just using a pixel perfect camera
Is it actually important that your character snaps to a grid
If you absolutely must do that
Then just let physics and rb handle all collision
Trust me coding collision yourself isn’t worth it
You can still snap the player to a grid when you stop moving even if you allow rb to handle physics
There’s nothing stopping that from working
because this 'complicated logic' was the bare minimum to code movement 10 years ago?
i was tryign to sort out how to use teh new input system and for some reason my collision code just isn't working for the top
how will a pixel perfect camera fix this? this sint about the camera its about the walls and my gird
what
how is that relevant
why do you need your player to actually have their in game position be on the grid
because i'm going for a rpg type gameplay, with events and interactables and i just wanted the old school pixel perfect feel?
The idea with pixel perfect camera is that it also snaps all the sprites, so even if the true position of objects is not on a grid it doesn't perceptually make a difference
This means the physics and collision could be handled by rigidbodies
Alternatively, if you're overriding transform position in your script, you're also overriding rigidbody physics entirely so you need to code your own physics, whatever that requires in your case
so scrap this and start again with a 'pixel perfect camera' tut? can i still use rule tiles with it or no?
Neither method is exactly better, though using Unity's physics and pixel perfect component is less work but harder to get exact results with
Rule tiles are fine, not related to physics or anything
You'd have to choose whether you want to design and tune your physics and pixels by hand, or rely on pixel perfect camera and rigidbody physics instead
i apparently CANT tue these by hand
Meaning?
As far as I can tell you're still a bit in between systems
If you do your collision detection manually, set your rigidbody to kinematic or remove it entirely
Then start troubleshooting all parts of your system, mainly does the overlap detect the wall correctly
It seems like it would not, if your character is not allowed to move if it does
(If you do use a rigidbody for your character, you are meant to use rigidbody class methods for moving it, so Rigidbody2D.position or Rigidbody2D.MovePosition instead of Transform.position
This shouldn't affect functionality, but to my knowledge improves accuracy and performance because rigidbodies are meant to be responsible for their own movement)
Hey! my pathfinding seems to not work properly, the agent's never pick the shortest path, instead they pick a random one
what can i do to make them always take the shortest path?
hello regarding optimization in a scene this big with lots of stuff in it my current optimization is to have data reading of each stage puck to be in a singleton and once read from db just pass it to each puck but its still kinda slow any more optimizations that can be done? it takes about a 1sec to 1.5 to fully load
#🤖┃ai-navigation is the best place to ask. you'll likely need to provide more detail on your setup and/or code
EPERM: operation not permitted, rename 'F:\Uni Work\Computing project\Computing project VR Unity Project\Library\PackageCache\com.unity.xr.management' -> 'F:\Uni Work\Computing project\Computing project VR Unity Project\Library\PackageCache\.del--21412-uGbm5poMmWEt'
UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()```
anyone know why any package i try to install fails with this error
actually some work, and i managed to install xrpluginmanagement forcefully by installing something that had it as a dependency, but most others still fail?
now unities forzen and has tried installing this one thing about 20 times
itll load, disappear, freeze a little, then pop back up again
ok so, anytime i open project settings unity maxes out my ram and freezes
it's fine everywhere else and lag has never been an issue before in unity
so i don't think it's my pc not being good enough
i've also got this error
The file might be corrupt or have a missing Variant parent or nested Prefabs. See details below.
Errors:
Nested Prefab problem. Missing Nested Prefab Asset: 'XR Origin (XR Rig) (Missing Prefab with guid: d6878e1999eb4b44a9f5a263af86c185)'
Nested Prefab problem. Missing Nested Prefab Asset: 'Hand Menu With Button Activation (Missing Prefab with guid: e2698219e3231e94c8765d49b9dd5cff)'
boy do i love when everything just breaks at once out of the blue and nothing seems to fix it
the package installing issue seems to have fixed itself but i still can't open project settings without unity dying and running 0.1fps, and im still getting an import error on a prefab
this is a code channel
where would i go for these issues
there's no general unity help channel though
then you didn't bother reading that
i did
it says go to
"browse channels"
which is just the list of all channels and i still dont see one for unity help
try reading more than just the first sentence you see
brother i read it all there's no unity help channel
you don't need to lie, it's clear you did not read past the very first sentence in that channel.
also you remember how in grade school your teachers would tell you to read all of the instructions before beginning a test or whatever? yeah, this is why
nowhere in there
does it say where to go for general unity help
copy and paste the second sentence in the channel i linked.
it says to use find a channel
i wouldn't count general questions and unity help as the same but ok
mate, general question that belong in this server are unity help questions because this server is a unity server. also nowhere in that does it specifically say "general questions" or "unity help"
i'm trying to make a editor script that sets the tilling for all new materials that have a texture located in assets/textures/surfaces to 0.3 x 0.3, can som1 tell me what i'm doing wrong, it does not return any errors
using UnityEditor;
using System.IO;
public class SurfaceTextureTiller : MonoBehaviour
{
static void OnPostprocessAllAssets(
string[] importedAssets,
string[] deletedAssets,
string[] movedAssets,
string[] movedFromAssetPaths)
{
foreach (string path in importedAssets)
{
if (path.EndsWith(".mat", System.StringComparison.OrdinalIgnoreCase))
{
Material mat = AssetDatabase.LoadAssetAtPath<Material>(path);
if (mat == null) continue;
Texture mainTex = mat.mainTexture;
if (mainTex != null)
{
string texPath = AssetDatabase.GetAssetPath(mainTex);
if (!string.IsNullOrEmpty(texPath) &&
texPath.Replace("\\", "/").ToLower().StartsWith("Assets/Textures/surfaces"))
{
mat.mainTextureScale = new Vector2(0.3f, 0.3f);
EditorUtility.SetDirty(mat);
AssetDatabase.SaveAssets();
}
}
}
}
}
}```
is the code even running?
what's calling this function?
i put it in the editor folder i thought unity would pick up the OnPostprocessAllAssets method and run it from there
ok so after changing the monobehaviour thing to assetpostprocessor the string array lit up and it runs but it still doesnt seem to change the tilling
howdy!
So in my game you pick up this clipboard and you can read it
It's a game object
but I need it to not be affected by light?
As you can see it uh.. Is clearly unreadable lol
put a world canvas on it
Oh I see i'll give that a shot thanks
What exactly is a 'world canvas'
I see normal cavas
Oh world space
gotcha
Oh wait you said 'on it'
not put it in one
yea
wdym ? you want the entire material of clipboard not to be affected by light
uhh if thats the case you'd have to use Unlit material
its going to look pretty out of place, if you want that look though should be ok
My shader settings are locked for the individual pieces of the board I was gonna try that
on mesh renderer
You'd have to duplicate the material or extract it from mesh to modify them
Wont that look bizzare..
iono.. thast how regular ink works
in a dark room with bright glowing text on a dimly lit piece of paper
Hmm you mighr be right
yo, for some reason when i bake, its not showing me what i baked? any ideas? i am using navmesh surface, and also i am tryna make a cube follow it, for some reason it isnt, i am guessing.
In this case its probably more realistic to pick this up and have to walk into light to read it
Fits more with the horror vibe I guess
line 16 has nothing to do with baking navmesh
either target or agent is null, or both
yup
most likely you put Robot on another gameobject where the fields are empty. Or its an old error you never cleared
lol we got the same clipboard model

Yeah haha it fits perfectly
btw if you want to make ur light a bit more realistic, you can use light cookies
https://docs.unity3d.com/Manual/Cookies-introduction.html
https://youtu.be/Z4pO4IpH0xU?si=PehGjpW5M0qn_ioA
i see
make sure u dont have clues on the paper that u cant read..
i will recheck, many thanks
like if ur flashlight runs out of battery and u cant read the next clue or something.. (softlocked)
if you want to search for it in the heirarchy you can write t:Robot
it will show all objects with that component
what about magic lights that Reveal special Ink 😏 ?
that works too 😉
National Treasure-esque
Lemon Juice and Blacklights
and that clue will lead to another clue. dont you see ? treasure is a myth
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed;
public float rotationSpeed;
private Rigidbody rb;
private float moveInput;
private float rotationInput;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
// Inverted vertical input so W = forward
moveInput = -Input.GetAxis("Vertical");
// Left/right rotation input (A/D or Left/Right)
rotationInput = Input.GetAxis("Horizontal");
}
void FixedUpdate()
{
// Move forward/backward
Vector3 move = transform.forward * moveInput * moveSpeed * Time.fixedDeltaTime;
rb.MovePosition(rb.position + move);
// Rotate left/right
float rotation = rotationInput * rotationSpeed * Time.fixedDeltaTime;
Quaternion turn = Quaternion.Euler(0f, rotation, 0f);
rb.MoveRotation(rb.rotation * turn);
}
}
How can i modify this code in order make my tank to can't reach high hills
!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/, https://scriptbin.xyz/
📃 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.
So this clipboard spawns in my face so i can read it
It has a box collider and so do all other objects
but i can put it through walls etc
Nvm just moved it as close to the camera as possible and made it scaled down
I considered that but the way it attaches to the camera gives it that subtle sway movement which looks really good
This is when you fudge the render order (to be after most opaque but pre transparent) + ignore depth or use a second camera to render it later.
ofc camera stacking is the easiest but then sadly you wont get Shadows from the world
Oh and sadly if one uses Deferred rendering , doesn't allow camera stacking :\
What's the best way to make a 2d interface in a 3d game? Should I just create some flat gameobjects and place them right in front of the camera?
Unity has UI packages
UGUI (the standard) or UI Toolkit (the latest and greatest but still not totally feature complete maybe)
Which of the two should I pick?
UGUI is the easiest to get started with as a beginner
I'm just hoping to do some sorta basic GUI stuff eg a panel with 3d models that you can drag into a building space
If the 3d models need to be dynamic/animated, it's a little more complex
if you just need images of them, you can create those images ahead of time and import htem as regular sprites to be used in the UI
That'd be useful, is that possible with UGUI though?
yes
The way works is basically using a second camera to render to a RenderTexture, then using a RawImage component in the UI to display the texture that the camera rendered
alright thanks
Alternatively if it needn't be interactive you can use a VideoPlayer
I have a question regarding cavases and issues with them, Can't find a correct place to ask, any help?
Thank you for the help on my script guys
no worries.. thats why we're here
(see what spawncamp linked about posting your code)
https://scriptbin.xyz/ heres a good one <- soup
Use Scriptbin to share your code with others quickly and easily.
Does that workN https://paste.mod.gg/tdvdpimkyhjx/0
A tool for sharing your source code with the world!
yup
Learning a bunch of stuff here haha, thanks a lot everyone
Ans such a fast response, you guys are awesome
i'm not seeing any debug logs there
depends on how hard we're procrastinating on our own projects 😉
-# <- has unity open and hasn't touched it in a few days
Even without having debug logs I should have something show up in the console, right?
no?
stuff doesn't magically happen, something has to cause it to happen
the console automatically shows errors and warnings, and probably a few specific logs, but anything else has to go through Debug
Where should I add debug then? And more importantly, how? 🙂
hi guys, i just installed unity and i'm following a course video on youtube. everything good until my new first script. i got this error, can someone help me? i would appreciate it a lot :(((
Understood. It showed absolutely nothing since day one though, that's why I'm a bit confused
well then there wasn't anything to show lol
- where it's relevant, aka where the issue might be. debugging doesn't solve issues, but it lets you narrow down where they come from and what might be the cause
- you can use
Debug.Log, and pass in a string, which would be the message of the log - use an interpolated string, like$"string content {variable}"which lets you peek into the program and see values. the "string content" part could be used to label where the log is from or what value you're logging
FYI here's the hierarchy window and the inspector for my sprite child
hmm real quick, since we didn't actually mention this - in the animator window, when you run, does isRunning show up as true, or does it just stay false?
I had this in my code at one point but removed it: // Récupère l’objet enfant "Sprite" (doit exister dans la hiérarchie)
spriteTransform = transform.Find("Sprite");
if (spriteTransform == null)
{
Debug.LogError("⚠️ L'objet enfant 'Sprite' est introuvable !");
return;
}
animator = spriteTransform.GetComponent<Animator>();
if (animator == null)
{
Debug.LogError("⚠️ Aucun Animator trouvé sur l'objet 'Sprite' !");
as i was learning i used them EVERYWHERE every function, everyloop, every condtion, every gameobject and value.. probably too much tbh but u sure get lots of information
those are indeed logs, but those would trigger only if you didn't have a sprite child/animator
- where it's relevant, aka where the issue might be. debugging doesn't solve issues, but it lets you narrow down where they come from and what might be the cause
- you can use
Debug.Log, and pass in a string, which would be the message of the log - use an interpolated string, like$"string content {variable}"which lets you peek into the program and see values. the "string content" part could be used to label where the log is from or what value you're logging
string interpolation is a game-changer
also for future reference, small snippets should be formatted like the latter half here:
!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/, https://scriptbin.xyz/
📃 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.
When I run, it stays on idle:
ok, that's not what i asked though
does the isRunning parameter ever change when you run?
small code blocks ^ like dis
And just to make sure I get it, are you talking about this?
yes
When I run, nothing happens animation wise, it stays on idle. I think I set up the isrunning properly and I'm using the exact same name as the one I have in my code
is this checkbox supposed to do anything?
you aren't answering my question... does the isRunning parameter stay unchecked?
it shows the value of the parameter (and lets you set it manually for the initial value or for testing)
yes it says unchecked
if (animator != null)
{
Debug.Log("Animator was found");
animator.SetBool("isRunning", direction.magnitude > 0.1f);
Debug.Log($"We just set the animator's isRunning boolean to: {direction.magnitude > 0.1f}");
}
yep ☝️ basic debug in this case
give urself as much information as u think u need that will help figure out little bugs and errors in ur code
though you'd probably also want to debug direction (and perhaps its magnitude to avoid having to calculate that yourself)
true.. i was hoping they had a variable for those
its own boolean..
same for the isRunning boolean..
i tend to use 1 for the script.. and then use that one to just set it directly for the animators..
I added the small code you gave me in the script and still nothing in the console window
nu uh..
u put it here in the fixedupdate??
if none of the code runs.. that means that that condition never evaluates as true
Here is the updated code: https://paste.mod.gg/yehjrsvntzro/1
A tool for sharing your source code with the world!
that means this MUST be null then
Oh wait can we co-edit the code on that website? 😮 that would be awesome if it worked
put an else statement on the end of it
Now you do have an error and you still have error messages disabled in the console
if (animator != null)
{
Debug.Log("Animator was found");
animator.SetBool("isRunning", direction.magnitude > 0.1f);
Debug.Log($"We just set the animator's isRunning boolean to: {direction.magnitude > 0.1f}");
}
else
{
Debug.Log("This is the only other thing that could be happening");
}
ya i thought i seen that too but couldnt tell for sure or not
the error message should have some info
wait guys it works!!!!
animator is null and still trying to be accessed
Oh my god I don't know why
thats not a good place to be at teh end of a debugging session 👀
lol
I re-applied the script to Player and I now have my run animation. Absolutely no idea why, I tried that a few times before...
well, glad we could help <question mark> 👍
that sounds like an unsaved script
yuppers
And I can see the logs!!!
Hawt Dogg! slaps knee
that's a lotta errors
@azure forum
yup he was gatekeeping the rest of the errors with broken code
now that its not broken anymore the flood-gates are open
Might've been yes, do I need to re-apply it to the game object every single time though? Or I just ctrl S?
ctrl + S in the IDE
and then when u tab to the Editor it should RECOMPILE
on its own
this thing ^ should pop up even if briefly
if not u'd want to manually Refresh Ctrl + R in the editor
I'll try flipping the sprite to the left with the script I found earlier, I'm confident it'll work now... hopefully
still should fix this btw
notice the "error" symbol (red octagon with !) is highlighted, that means they're hidden
best as a beginner to isolate things as u work
try it on a simple non-player object first
get it working.. then move it to ur player..
that way atleast if it doesnt work on the player.. u knew it did before hand.
wow 😮 seems like there were a lot of errors indeed
kind of a way to pre-debug
either that or its the same error being loggged multiple times
Will do! Thanks for the tips!
nothing wrong with using basic cubes and empty gameobjects to write some code 👍
I started with that but I didn't learn the code per say, I just found bits and pieces online that I put together. Time learn C# then haha
also. heres a tip.. u can Collapse identical debug logs.. that way they dont flood ur console..
it'll just add a number to the far right.. showing how many of those logs exist
with this button here
ohhh that's great! Much easier to go through indeed
yeah, stop using chatgpt and use real resources lol
see c# resources in pinned message, and unity resources in 👇
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
ChatGPT is better as an assistant than a tutor
I started the online course (learned editor essentials) but I wanted to try my hand at something in the meantime, to keep things entertaining
Anyway I'm really glad I could find a solution, and you guys helped me understand how it all works a lot better. I'll be sure to post here if I have other issues, thank you so so much!
ya, as long as ur taking steps forwards and not backwards you do you mate 👍
as long as they aren't intermeddiate or advanced yea
"code" and "beginner", seems about right
Im making a sliding mechanic in my game, and I used this line of code:
playerObj = new Vector3 (playerObj.localScale.x, slideYScale, playerObj.localScale.z);
and i have an error saaying: Cannot Implicitly convert type 'InityEngine.Vector3 to 'unityEngine.Transform
I am very new to this, and havent seen it before
for future reference, post formatted !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/, https://scriptbin.xyz/
📃 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.
and also, don't retype error messages. copy them. you may lost important detail when copying.
anyways, seems like you've declared playerObj as a Transform, but you're trying to assign a Vector3 to it - that's what the error means.
"I want a UnityEngine.Transform, but you gave me a UnityEngine.Vector3. I don't know how to convert this."
mhm
(backticks, the key beside 1 on a qwerty keyboard)
so i just need to use transform instead of Vecotr 3?
no, you can't construct a transform
playerObj = new Vector3 (playerObj.localScale.x, slideYScale, playerObj.localScale.z);
Error (active) CS0029 Cannot implicitly convert type 'UnityEngine.Vector3' to 'UnityEngine.Transform' Assembly-CSharp
what exactly are you trying to do with that code?
(only need the error message, fyi; the part between CS0029 and Assembly-CSharp)
from what the tutorial im watching explained it, it is shrinking the player, to a certain height, as its a slide, and then i add another line of code apling down force so im not floating in the air
so you're trying to modify the scale?
yes
so in that case, well... you'd have to assign to the scale, rather than the entire transform
(look at your tutorial closer)
compare that to your code
So i want to be able to jump while sliding, to be able to jump, i must be grounded, and ready to jump
When I'm sliding, grounded is not true
this is what sets grounded to be true
grounded = Physics.Raycast(transform.position + Vector3.up * 0.1f, Vector3.down, playerHeight / 2, WhatIsGround);
and this is my sliding movemnt ``` Vector3 inputDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;
rb.AddForce(inputDirection.normalized * slideforce, ForceMode.Force);
slideTimer += Time.deltaTime;
if (slideTimer <= 0)
StopSlide( );
how would i be able to make myself grounded when on the ground?
I cant figure out what the bug in my code is, or if the code is even in this snippet here. 😵💫 When this function is called, everything seems to be working fine except that ageInHumanYears always outputs 0. ageInDays works fine and so does ageInYears. The input for days is 8766. Can anyone spot any bugs I'm missing?
public static void SetAgeFromDays(Character target, int days)
{
target.ageInDays = days;
target.ageInYears = Mathf.RoundToInt(days / 365.25f);
if (target.ageInYears < target.ageOfAdulthood)
{
float percentage = (float)target.ageInYears / target.ageOfAdulthood;
target.ageInHumanYears = Mathf.RoundToInt(percentage * SimulationManager.Instance.ageOfAdulthood);
}
else
{
float postAdultYears = target.ageInYears - target.ageOfAdulthood;
float simulatedPostAdultSpan = target.ageExpectancy - target.ageOfAdulthood;
float percentage = (float)postAdultYears / simulatedPostAdultSpan;
int simPostAdultSpan = SimulationManager.Instance.ageExpectancy - SimulationManager.Instance.ageOfAdulthood;
target.ageInHumanYears = SimulationManager.Instance.ageOfAdulthood + Mathf.RoundToInt(percentage * simPostAdultSpan);
}
SetLifestate(target);
}```
Log all the values that are used to calculate it. If any of them seem incorrect, log all the values that are used to calculate that value and so on until you find the problem
I would step through with the debugger to see all the values here, line by line. This is usually the advice you'll get when asking about a bunch of math in a row.
Bet 🫡
is that a problem?
I beg to differ. LLMs are pretty good at explaining some things to me that I don't understand
When I move far enough away and stare at an object, it starts to disappear, and that's fine, but when, not seeing an object in front of me because I'm too far away, I get the idea of turning the camera to one side, I realize that I can still see it, and that's a problem.
Wahoooo it's working now!
Thanks yall
The calculation was based in years but two of the variables were using days. For some reason that made it output 0. Thanks for the tips on how to spot the broken variables >:)
While we're here, I've been gettin this Assertion failed on expression: 'IsInSyncWithParentSerializedObject()' UnityEditor.RetainedMode:UpdateSchedulers () ever since I attached the debugger. Should I worry?
You said you solved your issue but you can use TimeSpan to do time calculations easily (often ill advised to do it manually as you ignore stuff such as leap years and other things)
And if you ever need a real date time later if done manually you can easily produce invalid dates (e.g. manually changing the year +1 instead of adding 1 year)
I am using 365.25 for my variables, but I'll looking this up later!! Maybe it could save me some of my headache lol
this seems wrong in general? you raycast half the player's height but you start slightly above the player's midpoint (assuming your collider is centered)
did you miswrite a sign?
don't crosspost
Doesn't matter, still a bad idea and its incorrect as we use leap years.
C# has great date and timespan objects so use them!
idk then. didnt know its wrong in general cuz it works fine when not sliding 🤷
So like, im just starting Unity and C#. I am just wondering how would someone make a item skin system. I have the basic idea on how it works but how does a game remember. Does anyone know if there is a documention i could read?
I'm not really dealing with dates though ,,, this is a simple age int in my Character class. Days are being tracked with an int starting at 1 since we're not using real world dates, this is for a simulation
maybe you just set your playerheight too high, idk.
try changing the + Vector3.up * ... to a minus
But still, I'll take a look at this! Maybe I'm being stupid and these objects can help me out just the same
why not just ignore leapyears altogether then
🤷♀️
the ground check is not longer true when i set it to a minus
Could go either way. Will hardly affect the results. I guess it feels nicer? 😭
Then i guess you can take the simplified approach if it never needs to be real dates
sorry
Use a debugger, step through with the arg that causes the bad output and you will surely see what goes wrong 🦾 @tulip stag
and shouldnt you floor for your days to years check?
can you show how you're using grounded?
it makes it much simpler to deal with
public float playerHeight;
public LayerMask WhatIsGround;
public bool grounded;
void Update()
{
grounded = Physics.Raycast(transform.position + Vector3.up * 0.1f, Vector3.down, playerHeight / 2, WhatIsGround);
MyInput();
SpeedControl();
rb.linearDamping = grounded ? groundDrag : 0f;
// Handle jumping
if (Input.GetKey(jumpKey) && readyToJump && grounded)
{
readyToJump = false;
Jump();
Invoke(nameof(ResetJump), jumpCooldown);
}
}
The header is not right next to the Void update
i promise my code isnt that ugly
so i moved some stuff around, and fixed the locations of things, but now grounded doesnt check what so ever
A tool for sharing your source code with the world!
Are you sure playerHeight is big enough? Might want to draw the ray with Debug.DrawRay/DrawLine
Debug.DrawRay(transform.position, Vector3.down * (playerHeight * 0.5f + 0.2f), rayColor);```
i tried using this but no raycast apeard
and what is wierd, is when i drag the player up the groundcheck activates
so i draged orieantation up which is where things are linked to
and now i can jump, but that doesnt fix my original problem of groundcheck not being true when sliding
"Sliding" do you mean like on a ramp? Sounds like it's because the ground check doesn't quite reach into the ground in that scenario
just in general. i hit C and i get a speed boots, and my charecter size gets smaller
imgaine like ultrikill sliding
Oh interesting, maybe it's because of the character size part
Can't say for certain, just kinda spitballing possible problem areas
would you like the sliding script?
Let me see the ground checking stuff first
this is my move script
i should proppably add some explinations for future help
and there is some left over chat gpt notes i gotta reomve too lol
grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, WhatIsGround);
Looking here right now. I don't quite remember, what is the 3rd parameter for?
Is that raycast length?
yes
Gotcha
it takes the hight of the player and halfs it
That really makes me think shrinking char size might do something
can you guys listen to a begginer please?
My tank script doesn t work, because when i move backwards, it switches d with a and a with d. Forward is ok.
Here is the code : https://paste.myst.rs/en0k8alx
Here is how the gizmos are in local view:
a powerful website for storing and sharing text and code snippets. completely free and open source.
Cause then the raycast is smaller in length
Depends on what happens to them. Can you show an image of the guy sliding?
Im still on bean stage sadly
i have the camera as a seperate entiy and its position is linked to oriantation to avoid jitter and lag
Interesting. My thought was, it was shrunk, but maybe floating or something
But that's not what happens here
How thick is the floor?
Actually that wouldn't matter nvm
ill link my slide script for you too
A tool for sharing your source code with the world!
Try drawing a gizmo line that illustrates the raycast
like this? ```private void OnDrawGizmosSelected()
{
if (!Application.isPlaying) return;
Gizmos.color = grounded ? Color.green : Color.red;
Vector3 rayOrigin = transform.position;
float rayLength = playerHeight * 0.5f + 0.2f;
Gizmos.DrawLine(rayOrigin, rayOrigin + Vector3.down * rayLength);
}```
How would I go about making a machine assembling bay? What I have in mind specifically is an area where players are able to take different game objects(each part will have specific attachment nodes).
I'm specifically asking about how I would get around making different gameobjects clip together, or detect which part is connected to what, etc
Yeah something like that
nothing is drawn
Even when standing?
yep
Also keep in mind with that function i'm pretty sure you need the object selected in the scene
it is
I could have each gameobject object have a dictionary/list of open nodes and their positions, but beyond that I'm not 100% sure how I could actually take that data and move/rotate gameobjects accordingly.
Ok, for testing purposes, slap a debug.log before the early return. Make sure it's actually getting called
{
Debug.Log("OnDrawGizmosSelected called");
if (!Application.isPlaying) return;
Gizmos.color = grounded ? Color.green : Color.red;
Vector3 rayOrigin = transform.position;
float rayLength = playerHeight * 0.5f + 0.2f;
Gizmos.DrawLine(rayOrigin, rayOrigin + Vector3.down * rayLength);
}
like this?
nothing
Welp, there's our major problem eh? XD
yep
Doesn't seem to be getting called
but i can stilll jump?
Lemme see, there's a gizmo function I like using. One sec
WAIT
I don't think your gizmos are toggled on
how do i do that?
I'll show you, one sec
also i took some vids of what it looks like from my end
