#💻┃code-beginner
1 messages · Page 31 of 1
😄 yes somehow it does not allows
Nope but i wonder if it can get fixed
No, I'm asking you if the problem is really that the variable and method is the same name
You could check by just naming the variable something else temporarily to see
Make the compiler happy and do what it says
Thank you rat, wytea 
is it possible to add knockback force to a navmesh agent? Looks like they're conflicting setups. If a rigid body uses gravity and a nav mesh, itll work, but then the agent will slide. The only alternative i can think of is "turn off agent while knocked back coroutine is running" then switching it back on
I do dislike not being able to named my enums the same name as the type if they are nested within the class. :(
A* library has its own type of character controller for this situation.
still probably ways about it. Disabling the pathfinding as its knocked back does sounds like the solution, but you lose the feature of a character fighting against the pushing force.
Player goes through all objects, he doesn't collide with anything.
is this a good way of getting a percentage?
eyo why doesnt my Button work?
Do you have an event system in the scene?
ye
Hey guys, yet another problem from me ha
so, im trying to make a top down shooter, and my current goal is making the camera move in front of the player (relative to the player's rotation) when they scope in.
however, my problem is that sin() and cos() output positive numbers with negative inputs. this means that an angle of -45 is treated the same as 45, which makes the camera completely broken.
is there an easy way to fix this?
here is the code for the camera if you need it: (lineOfSightOffset is the distance from the player that the camera should be)
if (Input.GetKey(KeyCode.Mouse1))
{
// 1. Get the sprite's rotation Quaternion
Quaternion spriteRotation = Player.transform.rotation;
// 2. Convert the Quaternion to Euler angles
Vector3 spriteEulerAngles = spriteRotation.eulerAngles;
// 3. Extract the angle you need (in degrees)
float rotationAngleDegrees = spriteEulerAngles.z;
transform.position = new Vector3(Player.transform.position.x + (LineOfSightOffset * Mathf.Cos(rotationAngleDegrees)), Player.transform.position.y + (LineOfSightOffset * Mathf.Sin(rotationAngleDegrees)), 0);
}
else
{
transform.position = new Vector3(Player.transform.position.x, Player.transform.position.y, 0);
}
You want it to randomly break sometimes even at 100 percent?
Not sure what is going on here
The randomvalue part is what's confusing me
How come my lil loading screen still freezes with async scene loading seems like it alleviates it a bit but can I somehow always keep some time in frame for my loading screen script to run so it would be seamless
each item has a break probability when repairing, starts off at 0
and when repairing in the code above
i need to get a random percentage
and if its in the percentage it needs to break
but if its not you repair the item
and then increase the break probability
By saying it doesn't work I mean that player goes through all objects.
If it starts at 0, and you mutiply it by 0.2f it still is 0
what do i have to do
And it doesn't increase, it decreases
oh yeah
I dunno. You didn't really give any info at all. If you have an event system then it could be other issues
Show a screenshot of your inspector
With the button selected of course
wait i show you
wait i try something
no still not working
you dragged a scene object into the on click box of the button, right?
Also, show the code that is supposed to run.
Hey everyone i'm trying to make a first person shooting game but I want some cutscenes to make it switch to TPS, I've already prepared both cameras but I can't manage to change it in Timeline. I already did the cutscene animations and such
the problem isnt the script because no button is working
!learn
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
Hi. One question, what are those things called please? Like those things that go [] above the variables or something. Because I would learn more about them to be able to do some stuff with those variables under them:
Hmm, ok what are you dragging into the on click box? And also show a screenshot of the event system. I didn't see it in that video
Attributes
okay thanks
in the On click box is the script to load the next sentence
its for a dialogue
Ok, you can't drag a script in
It has to be an OBJECT in the scene that HAS the script on it
okay wait
do i use anywhere commands or there ic channel for them?
What?
Yeah there are
(idk where to ask them)
What do you need
is there channel for them
No
oh k
Oh shi- didn't know lol
🙂
Hey guys, yet another problem from me ha
so, im trying to make a top down shooter, and my current goal is making the camera move in front of the player (relative to the player's rotation) when they scope in so they can see further.
however, my problem is that sin() and cos() output positive numbers with negative inputs. this means that an angle of -45 is treated the same as 45, which makes the camera completely broken.
is there an easy way to fix this?
here is the code for the camera if you need it: (lineOfSightOffset is the distance from the player that the camera should be)
{
// 1. Get the sprite's rotation Quaternion
Quaternion spriteRotation = Player.transform.rotation;
// 2. Convert the Quaternion to Euler angles
Vector3 spriteEulerAngles = spriteRotation.eulerAngles;
// 3. Extract the angle you need (in degrees)
float rotationAngleDegrees = spriteEulerAngles.z;
transform.position = new Vector3(Player.transform.position.x + (LineOfSightOffset * Mathf.Cos(rotationAngleDegrees)), Player.transform.position.y + (LineOfSightOffset * Mathf.Sin(rotationAngleDegrees)), 0);
}
else
{
transform.position = new Vector3(Player.transform.position.x, Player.transform.position.y, 0);
}```
did you get it sorted ?
hmm strange, lets see where you left off
should I send code?
yeah use paste site
whats that
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
there's no need to deal with euler angles or trigonometry here.
its not that big though
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class BulletSpawn : MonoBehaviour
{
private float cd;
public Transform pTrans;
[SerializeField] private GameObject bullet;
public InputActionReference gamepadRight;
// Start is called before the first frame update
void Start()
{
gamepadRight.action.Enable();
}
// Update is called once per frame
void Update()
{
cd += Time.deltaTime;
if (gamepadRight.action.triggered && cd >= 0.5)
{
Debug.Log("Click worked");
Instantiate(bullet, new Vector3(transform.position.x ,transform.position.y,0),transform.rotation);
cd = 0;
}
}
}
I think my problem is with the instantiate
It probably is
transform.position = Player.transform.position + Player.transform.forward * LineOfSightOffset;```all you need is something simple like this^
Why not just move the camera forward to an offset times transform.forward?
Oh
Like praetor said
i not sure if that will account for direction
possibly, which object has this script on it ?
ill do it and get back to you
of course it will..? What do you think transform.forward is?
(this is assuming a 3d game btw)
its 2d
ok
hmm show the pivot of this object again
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class AIFollow : MonoBehaviour
{
[SerializeField] private GameObject bullet;
public Transform player;
private float time;
public float times = 1.5f;
public float moveSpeed = 12f;
private Rigidbody2D rb;
private Vector2 movement;
// Start is called before the first frame update
void Start()
{
rb = this.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
shoot();
Vector3 direction = player.position - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
rb.rotation = angle;
direction.Normalize();
movement = direction;
}
private void FixedUpdate()
{
moveCharacter(movement);
}
void moveCharacter(Vector2 direction)
{
rb.MovePosition((Vector2)transform.position + (direction * moveSpeed * Time.deltaTime));
}
void die()
{
Destroy(gameObject);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.CompareTag("Bullet"))
{
die();
}
}
private void shoot()
{
time += Time.deltaTime;
if(time >= times)
{
Instantiate(bullet, new Vector3(transform.position.x, transform.position.y, 0), transform.rotation);
time = 0;
}
}
}
Here is my ai script(It also does not shoot but does move)
doesnt work anyway
the thing is i just copied the button to another scene
use link instead
in the other scene it works
Show me the event system in that scene
what do you mean?
the red should be pointing the same way as barrel @echo dove
Send a screenshot showing the event system
and the green should be your Left side of character @echo dove
what is the event system?
how do I change it
That was my first question and you said you had one lol!
It's something you NEED for buttons to work
it works! thanks
Create one in your scene
righ click on player, make a new gameobject on the player, move it out of the player object after..Make sure now points correct way, put it back on your player and use that as your shoot-BulletSpawn script / origin
Was that other code GPT?
i thought transform.forward was another shorthand like vector3.up not sure why
Ohh now i know what you mean
nah copy paste from someone else in this channel, hence the comments
thank you im dump
The comments are why I thought gpt haha.
But yeah, it was a really odd way to do it
Edit: honestly, I bet THEY used gpt. Only it could come up with something like that hahaha
now it works
So I have to redo my model?
one thing i do want to know, is is there a way to modify transform.position.z without writing the whole thing as a Vector3 and changing the z part?
several ways
if its a sprite you can fix the pivot in sprite editor, it doesnt matter tho you can just make an empty gameobject for this just as Firepoint then use that in instantiate with a reference to that transform
Vector3 pos = transform.position;
pos.z = whatever;
transform.position = pos;
or use an extension method:
public static Vector3 WithZ(this Vector3 input, float newZ) {
input.z = newZ;
return input;
}
// THen you can do this
transform.position = transform.position.WithZ(whatever);
Or add somthing:
transform.position += Vector3.forward * amountToChange;```
I did this is this okay?
yeah that should work
show video how it spawns them
probably need to fix the bullet as well
the pivot?
show prefab for it
you try making a new bullet thats just a 2D circle sprite and see if it works
No shot...
So I should make a new bullet prototype
yep
Hi. Im struggling to make the pipes spawn in my flappy bird game. The pipes spawn but they don't spawn in the right place
its very strange thing that unity makes it default , it can cause such issues ..
I can show you the code
Yep thx so much for ur help
You have to show code
Ok
are you following that tutorial from YT
share !code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
He means send the code in a website
Yo could someone help me why is my instantiate not working...
https://hatebin.com/lrcsqnyqwk
like this
uh did you make sure the pivots are also correct now on the enemy ai lol
oh
i need help
What is dis
show the line 11
It's instructions for how to share code 🤷♂️
Missing semicolon
ur missing variable name
And name. Line 10
at least your IDE is configured
I thought it was some kind of error with my code but it is with my brain
what is IDE
oh okay
Nope my ai still doesn't shoot
ah wait sorry
Ok thanks
So you dont need help .-.
I need
alr
public class PipeSpawnScript : MonoBehaviour
{
public GameObject Pipe;
public float Spawnrate = 2;
private float timer = 0;
public float heightOffset = 10;
void Start()
{
spawnPipe();
}
// Update is called once per frame
void Update()
{
if(timer < Spawnrate)
{
timer = timer + Time.deltaTime;
}
else
{
spawnPipe();
timer = 0;
}
}
void spawnPipe()
{
float lowestpoint = transform.position.y - heightOffset;
float highestpoint = transform.position.y + heightOffset;
Instantiate(Pipe, new Vector3(transform.position.x, Random.Range(lowestpoint, highestpoint), 0), transform.rotation);
}
}
i dont know how to paste it better
I have a problem in my script in this part:
Debug.Log("New Player arrived");
GameObject playerInstance = Instantiate(PlayerPrefab, Vector3.zero, Quaternion.identity);
Debug.Log("Player spawned");
ConnectedPlayer.Add(NewID);
Debug.Log(ConnectedPlayer);
when I launch a second session of the game, I see the New Player arrived log looping in the console but I do not see the Player spawned and no player is instantiated. in the hierarchy I don't see any player appearing even in 0,0,0
@rich adder
alright, what problem are you having again
.
yea but we need to know what "in the right place" means
eg screenshot some spawn points, and where its spawning instead
basicaly some pipes are blocking the scene when they spawn and the bird cant pass
ill show you a pic
Two options here.
- On the second client, somehow
PlayerPrefabis null, which makesInstantiatethrow an exception, stopping the execution immediately (hence no log and no player instantiated). You'll get a "the object you want to instantiate is null!" error in the console. - The whole
ws.OnMessagehandler here runs in another thread, and accessing most Unity stuff (instantiating objects included) from another thread terminates the thread immediately without warning.
how do u navigate fast in rider to a class u know name of but dont have it used in code on hand for ctrl click like if ive got ClassA so I press some shortcut type that in and it opens me definition somewhere in my scripts
alr where did you place your spawn point at in the scene view
also show prefab for pipe
hi im trying to make a scene that plays a video, i want it to play the next scene when the video ends
but i cant
you can't why ?
click this and switch it to pivot
might be xD
top left
@jolly igloo your problem might be that the y offset is to big
make it smaller
ok
.
I changed it to 6 but it still doesnt work
obs
you changed it where in the inspector or script ?
script
you have to do it in the inspector
ok
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Bullet"))
{
die();
}
}
void die()
{
BroadcastMessage("check", 0);
Destroy(gameObject);
}
Hi I dont get it why this broadcast isn't working pls help
void check(float yes)
{
Debug.Log(yes);
if(yes == 0)
{
die();
}
}
the first is for my player
the second is my ai
I am trying to tell that when the player dies the ai also dies
Hey navarone can I ping you 🙂
@rich adder
not really lol
but uhhh I'd avoid Broadcast messages
Why are you using a float for this?
Should i not and if then what is the difference
alr 😭
why?
Just don't use that function at all, its slow / brittle
how Can I deliver messages or functions to others with an if statement
just reference the script and call the function directly
later on you learn about real events
like Action
or UnityEvent
Wait how do I do that
Het I'm trying to rotate a head along the Z axis. In the Scene editor it automatically adjusts for the position aswell. How do I do this in code when I just try to edit the Z rotation it goes around the player body.
This is the current code I use for rotating the head.
y = Input.GetAxis("Mouse Y");
Vector3 headCenter = bodyHead.transform.position + bodyHead.transform.up * radius;
bodyHead.transform.rotation = Quaternion.Euler(bodyHead.transform.eulerAngles.x, bodyHead.transform.eulerAngles.y, bodyHead.transform.eulerAngles.z + y * sensitivity);
public MyScript theScript;
or
[SerializeField] private MyScript theScript;
second one is better
your current function still doesn't make much sense
is there any way to execute a function even before the unity animation on android is being executed?
the unity animation on android ?
yeah
can I serialize DateTime
How do I check if the function was activated?
void check()
{
if (script.die)
{
die();
}
}
that doesn't work
a boolean
wdym
exacly... I need to charge something before that spash screen end... and even i make that splash screen larger the function awake is always executed a few miliseconds before that splash screen ends
the most basic logic in computer
hmm okay lemme mess around
true / false
is it okay for me to ping you next time if I need help
only if it pertains to a problem I've responded to, don't ping me for every issue you have lol
ok
other people here are very capable to respond lol
😉
what are you trying to do exactly with that ?
I thought of making a variable
and tuning it true when the player dies
thus have information from that variable and when it does become true the ai also dies
alright , only issue so far its private
I need to receive the response of the API we did yesterday before the splash screen ends
But Idk how to extract variables from scripts
oh ok
. dot operator
they need to be public
I knew about that
Seems like that was my problem
not sure on this one, maybe you need some type of hook. did you try searching the web ? its weird needing to do it like this instead of just doing it on a pre-setup scene
you should just keep this info stored on a enemy manager
so only 1 thing checks the bool
instead of all enemies
reduces code
so I should make the ai a prefab?
that too but I meant, a script that just manages all your enemies and checks if player == dead, then it just sets all enemies to dead
instead of all enemies checking for player bool
hehe, I'm taking advantage of the splash screen
thats more spaghetti then it needs to be
oh okay
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen)]
@rich adder so if this is the method i need to execute before the splash screen it will be something like this? ```cs
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen)]
private void Awake()
{
// Solicitar permisos de ubicación (puede personalizar este mensaje)
if (!Permission.HasUserAuthorizedPermission(Permission.FineLocation))
{
Permission.RequestUserPermission(Permission.FineLocation);
}
// Comprobar si se tienen permisos de ubicación
if (Permission.HasUserAuthorizedPermission(Permission.FineLocation))
{
StartCoroutine(GetLocationData());
}
else
{
Debug.Log("No se otorgaron permisos de ubicación.");
}```
no, definetly is not like that
hey any chance anybody knows how to switch cameras during timeline, my case I've a first person game which I want some third person cutscenes with timeline but I couldn't find how to swap cameras, I've 2 cameras ready (FPS and TPS)
I don't really understand what's the second options, and I'm sure that it can't be the first one because I don't get any warning or error in the console
also I tried with this code and here the player spawn without any problem
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TESTINSTANCIATE : MonoBehaviour
{
public GameObject PlayerPrefab;
GameObject player;
void Start()
{
player = Instantiate(PlayerPrefab, new Vector3(0,1,0), Quaternion.identity);
}
}
you probably dont want it on awake either
im trying to send the location of my turrent angle to a server in Matlab, heres my code: ```c
public class Server : MonoBehaviour
{
TcpListener server;
TcpClient client;
NetworkStream stream;
void Start()
{
try
{
server = new TcpListener(IPAddress.Any, 8080);
server.Start();
Debug.Log("Server started.");
}
catch (SocketException e)
{
Debug.Log("SocketException: " + e);
}
catch (System.Exception e)
{
Debug.Log("Exception: " + e);
}
}
// Update is called once per frame
void Update()
{
string message = Rotation.currentAngle.ToString();
Debug.Log("Data being sent");
Debug.Log("Stream: " + (stream != null));
Debug.Log("Rotation.currentAngle: " + Rotation.currentAngle);
Debug.Log("Client: " + (client != null));
byte[] msg = Encoding.ASCII.GetBytes(message);
stream.Write(msg, 0, msg.Length);
}
}
look into this
https://docs.unity3d.com/ScriptReference/RuntimeInitializeOnLoadMethodAttribute.html
@dry tendon
does anyone know how to stop a character falling through the floor? ive tried looking ways online how to stop it and its not doing anything. this is the code im using
im following this tutorial and everything worked fine until the last 5 minutes
#survivalgame #tutorial #unity
In this tutorial series, we will create a 3D survival game with Unity & C# as the scripting language.
We are going to start with basic FPS movement, build an inventory, and crafting systems.
Learn how to pick up items and more.
Little by little, we are going to add different features that are common to survival op...
now everytime i play test it i just fall through the terrain
first of all follow this
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
It's the second option then. Your websocket client/server here probably runs on a separate thread to not block Unity's code. You need to create a way to pass your websocket messages to the main thread (the one Unity runs on). Probably using a ConcurrentQueue<T>, that's a collection that allows cross-thread operations, meaning you can add elements from one thread and remove them from another. This definitely isn't a beginner topic though
you want to send angle to server but why you start a server in your code?
i have visual studio installed
yes but you need to configure it properly with unity. It will save tons of time debugging problems, read the bot link
also multiplying time mouse by delta time is wrong
remove that
i didnt make it its from a tutorial im following and everything was working until my character just keeps falling through the terrain
well the tutorial is wrong
and if you're falling through the floor then you don't have collider on floor, or you messed up the grounded layer
thank you for enlightening me on the problem , I'm gonna look what I can do with it, and yes you're right this seams not to be an easy problem , but I didn't know what was the problem and I was thinking that It was just a stupid mistake, that was I post it in code-beginner 😅
this is what the terrain looks like
there is a collider
inspector for the player object
like this?
sorry this is literally like my day 1 of coding and everything was working fine until now
Anyone? Pleasings? 🙂
So, in my case, what would you do here to have that number ready before showing a 0 when you get in the game? It takes so long to remove the 0 and add the number because that is the time it takes to obtain my location, send it to the API, and receive what the API sends me |Is the number next to the big 0|
i posted it
looks fine here, what did you change before it fell
I made a new layer for the terrain called ground
How I would do it, you can use async / coroutine to wait until that info has arrived until you load the scene
show player fancy loading or somehting
shouldn't take long since its an API call but those are ones you use async for this exact reason
you want the data to be ready before doing anything (ofc unless you have no connection or anything exception)
you put that ground in that layer when you created it ?
if i put the player up really high like this sometimes it doesnt fall through but it still stays up really high
i made a new layer on the terrain called ground and then made the player have a ground check
yes but did you put the terrain inside if ground ?
yes
can u show a video when it falls thru
@rich adder
https://hatebin.com/sjvsimkgkd
Pls this is according to the problem that you responded to and I get this problem.
[SerializeField] private PlayerCode script;
did you drag the playercode in the slot?

The ai dies but I get this message popping up
Hey I gtg i will be back in 10min
very likely its this line
public Transform player (guessing you destroy player when it dies)
also u already have player's transform thru this script now
PlayerCode script
oops
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 1f;
public ContactFilter2D movementFilter;
public float collisionOffset = 0.05f;
Vector2 movementInput;
Rigidbody2D rb;
List<RaycastHit2D> castCollisions = new List<RaycastHit2D>();
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void FixedUpdate() {
if(movementInput != Vector2.zero){
int count = rb.Cast(
movementInput,
movementFilter,
castCollisions,
moveSpeed * Time.fixedDeltaTime + collisionOffset);
if(count == 0){
rb.MovePosition(rb.position + movementInput * moveSpeed * Time.fixedDeltaTime);
}
if(count != 0){
print(movementFilter);
print(castCollisions);
}
}
}
void OnMove(InputValue movementValue) {
movementInput = movementValue.Get<Vector2>();
}
}
a screenshot of playerscreen with inspector expanded would've ben fine
In this video I will be going over a simple way to create pressure switches popular in games like Portal.
The system is modular so many switches can be added to a door so it requires a certain amount activated down for doors to open.
Apologies for the poor quality of voice recording, computer fans are very loud and messes with sensitive mic.
I ...
try keeping the sleeping mode to Never Sleep on rigidbody, see if it helps
Still the same thing happening
maybe it could be the sprite hitbox? i dont see why but just throwing it out there
How is it public transform player
I need that for the ai to navigate the player
And doesn't the ai destroy itself how come it is sending commands that it needs the players transform?
which layer is player in? maybe it needs to be in its own layer
default
because update is running so quickly that it probably tries to still get distance while player is destroyed
I tested it
it isn't coming from the ai it is coming from the camera xD
because when the player dies apparently the camera doesn't get any transform
anyways thanks
always hmm yeah always expand the error fully when you read it.
ok mb
usually tells you which script has error
thx
Can someone help me with this?
sorry i had to find a way to send it
are you sure ur not just spawning in the ground, lift it up a bit from the ground
also look the Y posiiton in playmode, does it keep moving?
how can i make foreach run once for every requirement? its in update ```cs
private void Update()
{
if(inputCell.item)
{
Item inputItem = inputCell.item;
IDurable durableItem = inputItem as IDurable;
breakText.text = "Break %: " + (inputItem as IDurable).BreakPercentage.ToString("F0") + "%";
foreach(var requirement in inputItem.GetProcess<RepairProcess>().repairRequirements)
{
templateName.text = requirement.item.itemData.name;
templateSprite.sprite = requirement.item.itemData.sprite;
templateAmount.text = "x" + requirement.amount;
GameObject newTemplate = Instantiate(template);
newTemplate.transform.SetParent(content);
templates.Add(newTemplate);
}
}
else
{
breakText.text = "";
if(templates.Count > 0)
{
templates.Clear();
}
}
}```
maybe check if the list doesnt already contain the newTemplate?
You moved the model but the collider (green) is still down there
Good evening everyone, sorry for this question, I would need some help regarding a mini project but since this is the first time I put my hand to code for VR I would like to know if someone could write the code for me so I can reverse engineer. I need to create some basic interactions for VR but without using external plugins, these interactions I need to take apart the bolts of a car and change the tire. If anyone can help me out I would really appreciate it.
When I start coding a game if I wanted to put it on steam would I have to code that game with that in mind?
how would I make something like Jackbox Games in Unity?
platypus perry, i have no idea who is jackbox games. Even tho i search, there is a bunch of games
basically they make these party pack games https://www.youtube.com/watch?v=_JyGUWviG2k
I ranked EVERY JACKBOX GAME from worst to best. Yes. All 45 individual game from the 9 party packs! With that many games to cover, there's bound to be disagreement, but I think any fan of Jackbox will enjoy!
►TWITCH: https://www.twitch.tv/Macro
►TWITTER: https://twitter.com/TheMacroShow
►INSTA: https://instagram.com/TheMacroShow
►MERCH: https:/...
Yes. You can
Hey everyone! Can someone help me with an issue with my game? In my game the player moves a box to catch balls. When the player moves too fast, the balls "phase" through the walls of the box. When the player moves more carefully, the balls stay in the box. How can I keep my balls inside the box? Here's a video and my the player script. Thank you!
You're moving the transform and by extension ignoring physics
Hi. I am having 2 errors but im unsure on what im doing wrong or rather how to fix it 💀 i believe my code is okay? i am not seeing where i miss spelled something.
start by getting your !IDE configured using the instructions below 👇
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
Ah ofcourse, I should use Rigidbody and AddForce
yessir
Guys what is this....
you're trying to access something that is likely private
I am trying to access a bool from another script
but it is public
show it
No, it's not
Like this right? i wanna use the 2019 version.
Recommend sicking to naming conventions and naming that bool IsMoving (which makes it sound like a question)
And is in PascalCase (uppercase first letter for each word)
@echo dove
That is only one step of it, but yeah
Okay
thx
Why should it be aquestion
I can make it Moving
because Moving == false;
or Moving == true;
Tells me the condition of moving or not
It's the naming, so you know it's a bool
Is the player moving? IsPlayerMoving or IsMoving
And it looks better in if statements if (player.IsMoving) ...
okay
Hi guys, my bullet is a prefab and I do not know how to give it commands from an object that isn't it just won't let me. That's why when the player stops (all stuff should be slowed down) the bullet doesn't. How can I fix this?
Pls help 😭
@echo dove
I know im stupid with this kinda stuff. but i think imd one now installing it?
well the tool path stuff is certainly wrong. you were only meant to change the first setting in that window
please actually read the instructions instead of skimming and assuming you know what it means
my first language is not english sorry.
well conveniently the microsoft website can be localized to a language you understand
im not sure how to move that
It might not always be accurate
really?
yes scroll all the way to the bottom, you'll see the currently set language in the bottom left
good point. i guess there's absolutely no point in trying then. they'll have to live with their unconfigured IDE and not get help here
xd
see #854851968446365696 for what to include when asking for help
never seen it b4. thanks man.
alr
!learn
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
visual studio is your IDE. it's for writing code. you need to configure it to use it with unity. having a configured IDE will provide you with autocomplete and intellisense. it will also highlight your errors for you and provide syntax highlighting for unity types.
having it configured is a requirement for receiving programming help in this server
ooohh.
once its 100% installed, my code should look different right? well, rather my code Visual Studio itself?
NICE. I have it fully installed now.
Wait but what is wrong with my question
and now you can use intellisense to determine how to make your rigidbody kinematic instead of attempting to use an enum that does not exist
not sure what is an enum, but alright i think i can handle it now that the IDE helps me
well you've not provided enough relevant information to determine the source of your issue
What other information should I give
Because I am not sure what is the problem here and what I should send
that is why I reached out here
SceneManager.sceneLoaded += (_, _) => mainCamera = Camera.main;
does this meme of a syntax have a name wtf im doing here
it's just adding a lambda as a listener to an event
the (_, _) is usually more like (param1, param2)
but you're using discards _ instead of actual names since you're ignoring the parameters
moving it doesnt change anything
aa cool
well this is a code channel after all. and #854851968446365696 specifically mentions how to share code
oh okay
yes it moves
so you're infinitely falling, you must be spawning / snapping under the floor. Check your positions/colliders
Hey guys, i'm trying to add bullet spread to my 2D top down shooter. however, the bullet keeps coming out at very peculiar angles when i shoot the gun. in the code below, which is the part that needs fixing, FirePoint is the point from which the bullet appears, and also is facing in the direction that the bullet needs to be fired in. can someone tell me whats wrong?
Vector3 BulletDirection = FirePoint.rotation.eulerAngles;
if (Input.GetKey(KeyCode.Mouse1))
{
BulletDirection.z += Random.Range(-bulletSpreadADS, bulletSpreadADS);
}
else
{
BulletDirection.z += Random.Range(-bulletSpreadHipFire, bulletSpreadHipFire);
}
FirePoint.rotation = Quaternion.Euler(BulletDirection);
GameObject bullet = Instantiate(bulletPrefab, FirePoint.position, FirePoint.rotation);
Rigidbody2D rb2d = bullet.GetComponent<Rigidbody2D>();
rb2d.AddForce(FirePoint.up * bulletForce, ForceMode2D.Impulse);
I FIXED ALL ERRORS! But i have a question. With all this + a physics material for making the player bouncy it should be able to jump right? I press spacebar and it does not jump.
Hi guys, my bullet is a prefab and I do not know how to give it commands from an object that isn't it just won't let me. That's why when the player stops (all stuff should be slowed down) the bullet doesn't. How can I fix this?
https://hatebin.com/hfwumdsqek (player code)
https://hatebin.com/vrfmksygyo (bullet code)
You did it! I have no idea about bouncy rigidbody
Pls help 😭
i have and i dont see anything wrong which is why im confused
Y position is negative (-0.73). Unless the ground is below that, you'll fall through.
i see, so i guess moving it doesnt change that. that fixed it, thank you 😅
Can someone explain the "MissingComponentException: There is no 'SphereCollider"" error please? Sorry, i do not understand it.
Hi! I'm generating a procedural world based on a seed. The world is subdivided in chunks. I need to generate a differend seed for every grid box, based on its x and y. How can I do that?
Something is trying to use a sphere collider but its not there
Hi could someone help with this pls
Anyways goodnight I hope someone could respond by that time
Sorry to ask, but do you know where can i search for that on the Microsoft page? im new to this. sorry.
Sphere collider is a Unity component, nothing to do with Microsoft
oh. my bad.
a super simple way would be to add the X and Y together and hash that and add it to the regular seed. this will end up with some repeats though where 1,3 and 3,1 would have the same seed so you'd also need some other way to differentiate such as maybe also the hash of the angle from origin to the chunk.
or you could choose something else entirely, you just need to choose something that will be deterministic
Hello everyone
I am not a beginner to C#, but please if someone can try to explain this whether it's in C# terms or simple unity terms
So the update method get calls once per frame
that means that if my pc is stuck to 60fps, that method will be called 60 times a second
so, if I have an array of 100 elements, and I loop it inside the Update method, that means each second I am looping 100*60 = 6000 elements
my question is, how does this work programmatically?
like each second, how does the CPU split the calls to those for loops? does it queue those loops and pass each one to a thread? what happens if one thread isn't done with its loop then time passes? does the thread skip that loop and jump to the next one assign to that second?
please refer me to any guides that discuss this, as I am not a game developer and I am trying to understand the effect of this on a large scale project
im trying to find to add the sphere collider to the floor but i dont see it 💀
the error is telling you that it needs sphere collider on Personaje
ON PERSONAJE?
yes
Yeah, it says it right in the error message
OOHH
Who reads error messages anyway :)
im going to rest. i cant even read that 💀
that loop will happen entirely on the same thread. unless you are setting up your code to run on multiple threads it will not do so. the unity API can also only be accessed from the main thread so unless you have an actual reason to use multiple threads, don't bother doing so.
your code will run sequentially so when update is called the loop runs to completion. no other code will be running during that time. then on the next frame the same thing happens
im tired man. i read half the stuff
hey errors usually tell you exactly whats wrong
i know. im just really tired.

Why do you have to add L to the end of a long value, D to the end of a double number, and F in front of a float number? I was thinking it was for identification but wouldn't the keyword before the name of the variable already do that?
Sorry about the basic question, I tried to google it but it won't come up
It won't have the type on the left every time. Sometimes you want to do something like:
Random.Range(0f, 1f);
No decimals, but you want it to be clear that it is a float so it returns a float
In an initializer, it is just a convention
Yeah, it's not like you do Random.Range(0f, new float 1) so there needs to be some identifier
actually do you need to put f if you make it with two decimals
I am not sure in that method. It may complain about it being a double. May not 🤷♂️
yeah true
Default type for a decimal literal is double, so it will complain
The postfixes are there so you don't need to cast the values to their correct type
was working on some old opengl version and was having to type out 0f and some of its functions which I thought was funny
12UL > (ulong)12
Moin again, can someone tell how, how i get
Directory.GetFiles(Application.streamingAssetsPath + 4th Folder + Filename)
?
So how do i do this 4th folder thing?
i don't know what this "4th folder" thing is at all
i have subfolders and i want to get the 4th one in my filepath, without knowing the name of it (because it can change)
Directory.GetDirectories
counts the Folders and now i want to access number 4
well, iterate over the directories in the Application.streamingAssetPath directory and use the fourth one
what does iterate mean?
this returns an array of strings
you could actually just pick the fourth one directly
to loop over things
foreach (var dir in Directory.GetDirectories(...))
but since it returns an array, you can just do Directory.GetDirectories(...)[3]
ill try that one
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
i have a issue with my game. the fire point is going out side the angle i assigned it. https://gdl.space/nigijesixo.cs
i feel my Brain looping on that atm xD
So i do
Amout_of_Files_in_Folder =
Directory.GetFiles(Application.streamingAssetsPath + Subfolder_1 +
Directory.GetDirectories(Application.streamingAssetsPath + Subfolder_1 + Subfolder_2)[Number]).Length;
... right? o.O
this is a mess. what are you trying to accomplish here?
hey everyone!
so im new to unity and im currently trying to get a simple input system for a 2D game. this script is basically supposed to use raycasting to detect when the mouse is hovering over a gameobject i have created known as a tile, and this object has a box collider on it.
however, the ray is not hitting it for some reason. i know its initiating the ray because the "RAYCASTING" debug log is sent, but nothing further than that is. any help?
void Update()
{
if (buildingBackend.getBuildMode())
{
RaycastHit hit;
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
Debug.Log("RAYCASTING");
Debug.DrawRay(Input.mousePosition, Vector3.forward);
if (Physics.Raycast(ray, out hit))
{
Debug.Log("it raycast");
if (hit.transform.parent.gameObject == Tiles)
{
Debug.Log("ITS A TILE");
currentTile = hit.transform.gameObject;
if (previousTile == null)
{
Debug.Log("its the first tile!!");
currentTile.GetComponent<TileScript>().displayPrediction();
}
else if (currentTile != previousTile)
{
Debug.Log("its a NEW tile!!");
previousTile.GetComponent<TileScript>().hidePrediction();
previousTile = currentTile;
currentTile.GetComponent<TileScript>().displayPrediction();
}
}
}
}
}```
I want to count the Files in Subfolder_2, without knowing the Foldernames. So i want to include them into my Filepath with their Positions
sorry if im interrupting something
that DrawRay call is going to shoot a ray very far away from the world origin, since you're passing Input.mousePosition as the "from" argument
the actual raycast looks okay, assuming that camera is indeed the camera that's rendering right now
oh the drawray was just me trying to see if the ray was shooting, forgot to remove it
yes it is
is this maybe some issue with layers?
Welcome to episode nine of this introduction to game development in Unity with C#.
In this episode we'll discuss the difference between global, object, and local space. We'll also look at how to parent, scale, and rotate objects through code.
Project files:
https://github.com/SebLague/Intro-to-Gamedev
If you'd like to support these videos, yo...
The default will hit every layer except "Ignore Raycast"
hm. can you think of anything else that could be causing this??
find a way to draw the ray where its actually pointing and see
oh wait a second
you should split this into a few lines. First get the directory name, then do something with it
does the Box Collider 2D component create a non-filled collider??
like, just the edge parts??
you forgot to include Subfolder_2 in the GetFiles call
oh, you're trying to hit a 2D collider
3D raycasts don't care about 2D physics whatsoever
a 3D raycast will never hit a 2D collider
If you just want to find if there's a 2D collider where you clicked, you can use https://docs.unity3d.com/ScriptReference/Physics2D.OverlapPoint.html
eyy yes it fixed it
I think my question was ment to be code-general, how can I move it there without double posting?
was simply my silliness causing the issue
just delete the original
how do i get the Name?
Directory.GetDirectories().Name;
?
this returns an array of strings.
i mean to store the result of GetDirectories(...)[3] in a variable, and then use it on the next line
instead of trying to cram it all into one line
@polar acorn do you have an idea of how i could improve it?(so sorry for the ping 😭 ) and let me know if i wasnt clear in something 😦
is there update method but for like always not only in play mode
Like on the gui?
executeAlways is what I needed not editor stuff wanted to set shader property so it would look right not only in play mode
ty
my child object of the weapon parent rotating pivot point isnt set to the parent object
how do i isolate the Foldername from the whole path in the String?
The pivot of an object doesn't change based on the parent. You rotate the parent and it'll rotate the child with it.
ye i realized i typed thta wrong
basically ive made what im trying to already in a different project but im making it again and i have it like the exact same but its not working
It's not exact if it's not behaving as before.
How pivots and rotations work is not a randomly determined outcome. That would make development impossible.
can i
String = "Hello" - "llo";
to get "He"?
no
but you can do cs string x = "hello"; string y = x.Replace("llo", ""); print(y); // prints "he"
what in the javascript is that syntax 😄
which syntax?
can i
name = Directory.GetDirectories(Application.streamingAssetsPath + "Folder" + MoreFolder)[Number].GetDirectoryName();
String = "Hello" - "llo";
it's not real syntax
i know
But it could be valid C# if string overrode the - operator
well it isnt until you plug it into javascript and god knows what the output will be
Combine strings to make a path using Path.Combine();
E.g.
string path = Path.Combine(Application.streamingAssetsPath, "Folder", "AnotherFolder");```
(with using System.IO;)
i need to get the name of a folder in a path, so i have to reduce the path from the string
no need to write it yourself
does
GetDirectoryName()
work?
why wouldn't it
'string' does not contain a definition for 'GetDirectoryName' and no accessible extension method 'GetDirectoryName' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
Of course not
it's not part of the String class
look at the doc I linked
Path.GetDirectoryName
but isnt a path a string?
Path is its own class
there is a parameter in that function called path which is a string
So
Name = Directory.GetDirectories(stringpath)[FolderPosition].GetDirectoryName();
?
no
why not? ^^
because GetDirectoryName:
- Is a static function on the
Pathclass - doesn't make sense there
since you're doing GetDirectories it's already returning directory names for you
there's no need for GetDirectoryName
So
Name = Name.GetDirectoryName();
?
what is Name?
can you give an example of what you're trying to do?
The things you're writing are confusing and not consistent
GetDirectories returns the full path, not the name, thats why i need to isolate it
So the Idea is:
GetDirectories[Position) --> Path
and then
Path - Path(exept Name)
like if you have a folder:
Folder
Subfolder1
Subfolder2
What are you inputting and what are you trying to get out?
Name = "Subfolder1"
thats what i want name to be
that's the input?
Or the output?
what do you already have and what are you trying to get?
ok and what information do you have that should result in you getting "Subfolder1" out?

i have the Path and i want to get the Foldername
you have the full path?
and you just want the last part?
yes
yes
Thats the Idea of
Name = Directory.GetDirectories()[FolderPosition].GetDirectoryName();
you can do cs string folderName = new DirectoryInfo(Directory.GetDirectories()[FolderPosition]).Name;
or in general:
string folderName = new DirectoryInfo(fullPath).Name;```
https://hatebin.com/oqfusvdlpj
how come the animation keeps playing continuously?
there's nothing in this code that does anything related to any animations.
i have a issue with my game. the fire point is going out side the angle i assigned it. https://gdl.space/nigijesixo.cs
other than animator = GetComponent<Animator>(); but that doesn't affect anything - just gets a reference to the Animator
o.O
:-}
looks good
32- 25
that's telling it to enter one of the animator states. The behavior of whether it will repeat or whatever will come down to how your state machine is set up
nothing in it should make it repeat iself
weird
You are adding a random amount between -10 and 10 to the rotation of the firepoint. There's nothing preventing or limiting it from achieving any angle
you'd have to show how the state machine is set up
if loop time is enabled, would that make it repeat automatically when played
if there's nothing telling it to transition out of that state, it will stay there
I actually don't recommend rotating firepoint at all. That's not a good way to add spread
thats what im trying to figure out
just add a random rotation to firepoint's rotation and use that for the projectile.
no need to modify firepoint's rotation
Ok, one more thing, is there a way to exclude meta files in the editor version, so i dont stuble across these all the time?
Try this:
Quaternion rotation = firePoint.rotation * Quaternion.Euler(0, 0, Random.Range(-10, 10));
Rigidbody2D bullet = Instantiate(bulletPrefab, firePoint.position, rotation);
bullet.AddRelativeForce(Vector2.up * bulletForce, ForceMode2D.Impulse);```
note i made changes to all three lines, don't skip anything
wdym "exclude meta files in the editor version"
from this code?
what is this code supposed to be doing?
how can i have a trigger activated once button is clicked, but after the animation the trigger is reset
when i have an mp3 file in my folder and i wan to access it through the now done code, i stuble in the editor version across the mp3.meta files
triggers reset automatically as soon as they are used
oh
what folder?
It shouldn't be in any folder that would result in a meta file being there
the one we just found with the GetDirectoryName thing
if you're reading it like this, it needs to go in the streaming assets folder
there it is
thanks for the help @wintry quarry
I guess the better question I have is - why are you accessing it based on a position in the directory rather than... say... name or something?
oh ok, how then do i make where if no trigger is active, then its in the default state
cause its looping the attack state
once the trigger is active once
it needs a transition back to default
all you need to do is put an unconditional transition from the "Melee Weapon Slash" state back to the idle state
long explanation^^
anyway, can i just say
Name = "Hello.mp3.meta" - ".meta";
?
is there not a way to reduce strings?
I explained how to do that earlier
yea? now i need to scroll^^
thanks
So
if (Name.Contains(".meta"){Name = Name.Replace(".meta", "");})
right?
but i wanna keep the mp3 extention
it will keep it. I'd do more like:
if (Name.EndsWith(".meta")) {
Name = Path.GetFileNameWithoutExtension(Name);
}```
meeeh, but i think this Path thing is taking the whole path again and not my now carefully cutted string name o.o
or :
if (Name.EndsWith(".meta")) {
int extensionLength = ".meta".Length;
Name = Name[0..^extensionLength];
}```
Does this work? I think it works 😉
2 Points, what do they mean?
[..extensionLength]
ah ok
i think that worked, but it seems like somewhere else is still something wrong, but thanks :)
can't you just skip the meta files entirely?
since the actual files will be there
in the build, i will not need this line of code anymore, because the meta files will not be there anymore, but for developement in the editor, ill need this line. i fixed the mistakes now. But for some reason the functionality of my random function has changed xD
but, as a Pro-Programmer ... i dont ask why xD
i am really, really, really getting the feeling that you're doing things the wrong way here
you keep asking questions about doing very strange things with file paths
yeah - feels very XY problem to me
isn't this one of the examples on the XY problem website
<n00b> How can I echo the last three characters in a filename?
<feline> If they're in a variable: echo ${foo: -3}
<feline> Why 3 characters? What do you REALLY want?
<feline> Do you want the extension?
<n00b> Yes.
<feline> There's no guarantee that every filename will have a three-letter extension,
<feline> so blindly grabbing three characters does not solve the problem.
<feline> echo ${foo##*.}
ok, not exactly, but,
haha quite similar
https://hatebin.com/whcoqziqhr what is this weird behaviour I have to move mouse around for it to run or it just stop altogether is it something to do with Time.deltaTime or update method or what how can I make it run properly in edit mode. It should fade in/out constantly as in the start
The scene view will only update when it needs to
Update doesn't run all the time in edit mode
I don't think "Always Refresh" affects that
It looks like you're doing some smoothing on the colors. If you want to preview them outside of play mode, I'd just disable smoothing when not in play mode
no I want to see that smoothing in edit mode too
im back at square one for a method which runs in edit mode like update does in play mode 
That's because you marked them as trigger
Hey guys i have a question. How can i make so my character can double jump? I have this code but it makes it so you can jump every time you want to.
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
alr. thanks bro
add a "cs" behind the first to format it
like that?
like this
```cs
code
```
oh
// indicates a comment in a lot of languages
so you will frequently see it used as a placeholder
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SaltoJugador : MonoBehaviour
{
public LayerMask capaPiso;
public float magnitudSalto;
public SphereCollider col;
private Rigidbody rb;
void Awake()
{
}
void Start()
{
rb = GetComponent<Rigidbody>();
col = GetComponent<SphereCollider>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && EstaEnPiso())
{
rb.AddForce(Vector3.up * magnitudSalto, ForceMode.Impulse);
}
}
private bool EstaEnPiso()
{
return Physics.CheckCapsule(col.bounds.center, new Vector3(col.bounds.center.x, col.bounds.min.y, col.bounds.center.z), col.radius * .9f, capaPiso);
}
}
if (florp) {
// reticulate the splines!
}
thanks guys
im using this to jump, but i can do it every time i want to. How can i make it so i can double jump?
As for your questions:
You raycast to the ground, if the raycast hits and is short enough for your character to (barely) touch ground you set a variable grounded to true and a counter to zero
if you jump grounded goes to false and counter goes up, you can jump while either grounded or counter < jump count
first step is make it so you can only jump on the ground.
Once you have that figured out, modify it slightly to allow one single jump when not on the ground
So basically, a totally new script besides keeping this one 🤔 thanks.
not really
i can do it on the same one?
you just need to add a grounded check for the first part
why not?
They already have a ground check
"EstaEnPiso"
oh they do have a ground check
Oh yeah right
You should also configure your visual studio so that it recognizes Unity stuff
thats weird. i did it today.
Maybe you opened the script outside of Unity. Look into it later. I don't want to derail the debugging
yeah i think that was it. lol. closed and opened and it is okay now.
So can you jump unlimited times now? Cause your script already checks if you are on ground
i can jump unlimited times.
is your SphereColider way bigger than your character?
or not positioned to its center
You also need to configure VS !ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
i did i did.
not sure what happend on that screenshoot.
let me see real quick
no. the collider seems fine to me.
The checkcapsule seems kinda oddly set up.
You go from the center and use the bounds and all that but you only really care about right below you
I would do a checksphere at the feet with a small radius or raycast
Oh i think I know what happens, the end part of the Physics.CheckCapsule is absolute, can you debug log us the col.bounds.center?
uuuhhhh
double uuuuuhhhh
im unsure on how to do that let me google it rq
What it tries to do is check from center of the character collider to the bottom of it + some spare
Add Debug.Log(col.bounds.center) in the ground check
above the return line
the ground check was line 23 right?
the "if input" blabla?
oh above the return one okay
is there a way i can have the player's full sprite be shown in another menu, like even with all the attatched sprites in the child objects?
Here. I jumped 4 times.
You would need to either clone the player or render it with a secondary camera
how could i clone the player?
instantiate it in the menu and make it unable to move?
Is your character a fixed height?
if u want scene player to show up in ui view can u really clone that
my character is just a regular sphere.
it can bounce tho.
but i dont think that has anything to do with the infinite jump
Instantiate is used to clone an object. But that will copy all the script components too, so you have to remove/disable those.
I would just render it with a secondary camera
how could i render it with a secondary camera
2D game btw
If you can jump in the air, that means that your ground check (EstaEnPiso) isnot working correctly.
Add a camera with a rendertexture
Ohhhh I know the problem now, your ground check detects your character as ground
Keep it on,or disable it and manually render it with camera.Render()
wait what
why
ooohh
and set that in the script for the ground check
You can draw the rendertexture with a RawImage component @acoustic arch
could i not make my player a new layer that is player also?
man thanks a lot
Yes that should work
but you will detect ALL objects that have default as ground then
if you add a weapon and forget to change layer -> detects as ground
oh ok
so maybe both then!
alright. thanks a lot man.
Oh yeah, you still need help with the double jump you came here for initially or you gonna figure it out on your own now that the ground check works? 😄
i think i figured it out
anyone have tips for displaying my 2D character in the inventory, with all the child object sprites on it too
one option would be a render texture: you'd make a camera that renders ONLY the player
you can render onto a texture, instead of the screen
and then just display that texture
yeah that sounds alright
how would i do it?
https://img.sidia.net/ZEyI5/qUcEXAnE78.mp4/raw
using Sirenix.OdinInspector;
using UnityEngine;
public class InstanceTest : MonoBehaviour
{
public GameObject Instance;
[Button]
public void Spawn()
{
Instantiate(Instance, transform);
}
}
Just call instantiate on an already existing object, it will copy it 1:1
would that update in the menu?
Create a RenderTexture asset. Add a new camera that targets that render texture. Set its Culling Mask to only render the player's layer (you may need to create a new layer for the player here)
Then you can use the RenderTexture anywhere that a normal texture would be used, like an Image component
What menu do you mean?
Also be careful, that will also duplicate all scripts
it sounds like you want to display the player in a UI
in that case, you would need to be able to draw the player in an Image
yes
I guess you could try just gluing the entire player object into the inventory menu
how do i make the camera only target the render texture
assign the render texture here
But the UI would, by default, draw on top of the player. So you'd need to use a "Screen Space - World" UI.
oh ok
and it will update as the players armor and other stuff changes on the player design?
indeed
oh cool
Assuming all of the player's gear is being rendered by the camera.
You might just have a layer that all "entities" are on
not just the player
that would be close enough
how do i use the RenderTexture
.
https://youtu.be/O6_i4BOaLtM I made a better particle system for the bat attack what do you think?
keep the embers?
I finished big hit zombie, should I keep the flames on the bat?
or no flames?
Made this YouTube video for you to see it.
Big hit zombie boss from zombie castle app game, with flaming bat.
i can just select it inside where the player image in the inventory is
ah ok
RawImage can't do everything an Image can (e.g. it can't do a sliced or filled image)
but it can use any texture
just change the output?
That channel, or #archived-game-design
thanks
set the camera's "Target Texture" to your render texture
Hi so im trying to make it that if my player presses a key it enters a door. but the problem is when the person hits the key while inside the collison box it does not work, it only works if the player holds the key and then enters the Collison box. I want to make it that it only happens if they are inside the box.
OnTriggerStay2D
that method only gets invoked once: when you enter the trigger
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
it's kind of like using GetKeyDown instead of GetKey
ah ok I see.. but like I used OnTriggerStay2D but its still the same problem
Like im trying to have it when the person is inside the collison and when they hit the key then the operation happens
Hmm. It shouldn't. It will run every frame the person is inside the collider
oh wait it does work but I have to be moving inside the collider for it to work
oh, this is 2D
i know that rigidbodies fall asleep...very aggressively
consider setting this to "Never Sleep" on the player
💤
I do very little 2D, but I found out about this while helping someone with a similar problem once
Rigidbodies being able to sleep is a good thing -- it means the physics system can stop worrying about them until something hits them again
but it messes up trigger colliders, and there's generally just one player
not 300 of them
ohh ok so like will it then take less memory or like resources then
i only intend on using on the player
Less processing time.
The rigidbody is sleeping, so it doesn't need to have forces calculated
alright thanks for the help again
np!
Im making a 3d characters camera rotate based on the delta change of the camera, but at the start it has a huge shift and sometimes messes up the camera rotation
is there a way to set the cursor to the middle so it doesnt do that?
i set the cursor to locked in start but that doesnt seem to fix it
I wonder is it possible to do anything so my lil rotating icon wouldnt freeze when loading scenes and running all the awakes/starts and such
For loading scenes, there's async loading. For awake and start, you might need to spread your initialization over several frames if it takes too long.
how can you spread it over some time
I guess spawning in gameobjects little by little
You can make awake/start into coroutines or async methods.
Identify the scripts that take most time to initializes and spread them over several frames. If it's spawning objects, yield after a certain number of objects is spawned.
Could also maybe use the system time to yield after certain amount of time(like 10ms) or something
Aaa cool ty
Trying to make it so camera rotates 90 degrees by pressing keys, and it works when I'm trying to turn right (d key). But whenever I press "a" the camera spins infinitely, what's wrong with my code? https://paste.ofcode.org/ZqMdFiMZbbsi2wVJ3kRXck
You can't take the current rotation from transform.eulerAngles. You need a separate variable to track that.
Yeah, also MoveTowardsAngle instead of MoveTowards @fluid mural
So it loops around 360 degrees correctly
hi, how can i create and work on an instance of a material? I have a shdaer and i want to have different texture for each unit slot
private Material mat;
private void Start()
{
mat = unitImageGrayScale.material;
if(mat != null )
mat.SetTexture("_MainTex", unitImage.mainTexture);
}
this doesn't work its still not an instance
A renderer holds reference to it's material. When you use the material property, the renderer creates a new instance of the material.
Check the renderer component documentation.
Ah, if it's an image it's a different story. You can't mess with the material as it uses a different workflow. UI rendering is handled by the canvas.
If you just need to set a sprite for the Image component, it has a property for that. No need to access the material.
I dont want to set an image
I have a Grayscale Shader that takes Texture2D
and i want to get the texture from the sprite of the Image and assign it to the shader's material instance
because right now it changes to the same texture for all images :/
and each slow has different unit assigned
okay nvm _MainText automatically gets it from the image
solvd
does unity have builtin methods for manipulating sprites? like flip horizontal/vertically?
They have flipX iirc. Not sure about y.
how?
it's on the sprite renderer
ah yea, me dont wanna use that :>
so i was curious if there's something like SpriteUtility something
yeah im not too sure how it works on the sprite renderer
but if it's flipping the UVs, I guess there's some extra logic to keep it instance independent
actually theres an actual spriteutility class lol
probably modifies the mesh UVs or something
just not useful for this though
Good evening everyone, sorry for this question, I would need some help regarding a mini project but since this is the first time I put my hand to code for VR I would like to know if someone could write the code for me so I can reverse engineer. I need to create some basic interactions for VR but without using external plugins, these interactions I need to take apart the bolts of a car and change the tire. If anyone can help me out I would really appreciate it.
That's a really big ask. I doubt you'll find anyone willing to do that.
You'd have more luck if you tried it yourself and then asked specific things when you get stuck
Hello, in if, I wanted to make sure you must have these conditions. I used "&&" for that, but does not work. Is there another way to address this issue ?
just use SpriteRenderer.flipX
why do you want to do it on Sprite type
Sprites themself don't have "flip" properties
Dash isn't consistent! I'm calling the Dash function on PlayerInput script. How can I call it in FixedUpdate (because this is physics based)
private IEnumerator DashCoroutine()
{
canMove = false;
isDashing = true;
rb.velocity = direction * dashSpeed;
yield return new WaitForSeconds(dashDuration);
rb.velocity = Vector2.zero;
isDashing = false;
canMove = true;
}```
You first need to configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
Then note that SetActive is not a condition. The function returns nothing
Oh ok. Thanks.
Should I multiply the velocity be Time.DeltaTime or FixedDelteTime?
the unit of velocity is already m/s, if you multiple it with time it will becomes m, ie displacement
By the way, which should I choose in the 3 options ?
I'm in Mac.
Ok, I already did this. Where do I note for the SetActive condition ?
what condition, there is no condition, the method returns nothing. Did you mean to use .activeInHierarchy or similar?
Yes, exactly. In Hierarchy.
hi guys! I am trying to spawn my players in random places but it seems I have some issues with Random.Range and I don't quite understand why my editor is not happy with it. transform.position = new Vector2(Random.Range(positionRangeSpawn,-positionRangeSpawn), Random.Range(positionRangeSpawn, -positionRangeSpawn));
I keep getting this "'Random' is an ambiguous reference between 'UnityEngine.Random' and 'System.Random'"
yeah, read that..but I still don't undestand where is the issue and what should I remove / replace
Are you using the System namespace?
yep
oh
If you need it, specify the namespace you're using either via an alias, or when you access the type
I have a question. If I define the boundaries of an object in the start method, through bounds, and then bind these boundaries to a certain point, which will take the rotation and position of the object on which the script hangs, will the boundaries be superimposed on the object?
Because if you run an update in the method, then the boundaries will not be bounds, they will not follow the object, but will be, as it were, like a cube described around the figure, which does not change its rotation, which means that it will not actually be superimposed on the object, along its boundaries.
I just have a cube for which I need to constantly know the positions of the upper corners, and if I use bounds, then during rotation the points are not in the right place
Can I define bounds once in the start method and then bind them to a point?
use an additional bool to guard
Run it when you change durability
I mean when the durableItem.Durability gets changed
and you can write as follow:
if(x is A a)
the problem is that i run it the objects in player hands
like gun script
so the item doesnt know which slot its in
only the slot knows what item its holding
so look i got this gun script
and in my hotbar manager i handle like enabling the correct game objects in players hands
and OnEnable i cast the item
and when i shoot i just do this
wait you check durability of holding item in update? i think you can change it to event driven
Thats what im saying
yes
but then what about items for example which have the durability decay?
like food items
over time the durability will decrease
timer in update
Sounds like you need to redesign your item system a bit
you can update all registered items in slot (btw not sure your code structure), if the item is broken or expired then deregister it from your slot
I have a cube with 3 lanes similar to subway surfers. When I click A I want the player to move to the left lane and D for the player to switch to the right lane. My script somewhat works except sometimes my input doesn't register and it just sometimes glitches and doesn't respond how I want it to. What's the problem? https://hatebin.com/mrgynyiqfr
Nothing wrong with that code. Do you have other code that also affects the same game object?