#💻┃code-beginner
1 messages · Page 525 of 1
ahh gotcha gotcha.. 👍
its saying true
i just tried restarting unity to see if it was just being weird but its still doing it
Double check with ``Debug.Log($"{rootObjects[7].name} {rootObjects[7].activeInHierarchy}");`
Though I suppose we should check the CamContainer too
yea these are both true
Debug.Log($"{rootObjects[7].transform.GetChild(0).name} {rootObjects[7].transform.GetChild(0).gameObject.activeInHierarchy}");
still all true
sorry if this is annoying u btw
Running out of ideas. You are running these from the Start method with the GameObject.Finds?
yeah
at this point its probably just a bug or smt cos it should be working
ive tried tagging the objects to find them and using findgameobjectwithtag and it wasnt working either
@delicate zinc Can you send the current code and the full error you are getting
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
This is a coding channel #🔎┃find-a-channel
show CamContainer inspector
!collab
: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
It I need help wait one thing
then ask your question in a correct channel, if it is about modding though, do not do it as we do not do that here
It code
And adding it to the model
adding a script to a gameobject?
I try 100 of times but still
Take a moment, formulate an entire coherent question in a single message, then ask it
On ph
I do not know what that means, are you getting an error?
No I just need the players script and how to insert it
drag it onto the gameobject
I try taht and I not have a script
do you have a script made?
You have to make the script first
Then make one
go into the project window and rightclick -> create and make a new script
or you could make one in the inspector, nobody does that though lets be real here
Please watch this video and stop spamming this channel https://www.youtube.com/watch?v=WbtM6QCKyxY
After you're done, !learn Unity
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
is Unity Learn the best place to start to learn Unity-relevant coding, or should I branch out to general C# tutorials on, let's say, udemy or codeacademy?
{
if (allUpgradesById.ContainsKey(upgrade.Id))
{
throw new Exception($"Duplicate upgrade Ids: {upgrade.name}");
continue;
}```
Does throwing your own exceptions break the program? I basically just a more attention grabbing Debug.Log
Or does it just continue along no problem
throwing an exception means that the method being executed halts there, which of course makes that continue; entirely pointless since it can't continue past that point
I like exceptions because they are easier to spott in the console. Is there a way to get that without halting anything?
Debug.LogError
Debug.LogError
or just use rich text tags to make your logs standout more (or both)
So what's even the point of throwing your own exceptions?
Throwing exceptions is definitely not something to just do casually. It stops the entire control flow of the program
rich text + ur own static logging class ftw
To handle exceptional circumstances. Usually around file processing or something where you can handle it e.g. by showing the user an error message. Like "your save file is corrupted"
What's the benefit of the custom logging class?
Or "could not connect to the multiplayer server"
for me its so they stand out..
i can call Dbug.Green("ForExample"); or Dbug.Yellow.. and then its just rich-text in a regular Debug.Log
when something happens where you can't continue in code, like praetor mentioned, exceptional circumstances that shouldn't be happening
exceptions are a way to escape the code entirely to ensure that it doesn't break more from what's already going on
Continue is redundant if there's no code that will run after it in the loop.
How much do you guys use exceptions?
Rarely in game dev
not typically in game dev
Depends what you mean by "use" though
yeah it doesn't seem useful unless things get very complex maybe
I handle existing exceptions like file reading exceptions all the time for saved game systems
i don't have a ton of experience to back this up, but from what i do have, they're more relevant for longer, contained processes, like data processing
With try catch?
Yes
well, exceptions exist as part of the language, not part of unity
they have their use cases
Some languages don't have exceptions BTW. C and Go for example use a different approach.
and some interfaces use a similar approach to that with signaling return codes
Int.TryParse, the return value indicates whether it was valid or not instead of an error
or Physics.Raycast
or having both a successful value and error value be possible, like NaN from invalid floating point operations
these all encode "error" states without using exceptions
exceptions are more to control flow than just representing states, they have specific behavior like bubbling up
Whenever i change the jumpPower Float the jump hight doesnt change could somebody tell me why
you are declaring it again under JumpKeyWasPressed, remove the float next to it
because you declared it as a local variable
Why would it? You aren't using it anywhere
Oh thanks
hi, is there anyone who could answer this: is it possible to make 2 certain scripts that both disable a certain gameobject without overriding one another. Im currently making 2 hiding spots for my game: a table and a locker, the locker seems to work perfectly fine and disables the player within the scene but the table doesnt seem to do so?
im pretty new to C# and unity in general so please go easy on me
i dont think im the only newbie in the chat here
Put a third script on the object you want to disable that the first two reference, and have each one tell that script "Hey, you're supposed to be enabled/disabled" and have that third script keep track of how many things are telling it to be disabled. If any of them are still telling it to be disabled, it should disable the object
i was recommended to do everything into one file because i was pretty much repeating myself in the second script
like in a static way?
i actually havent come up with that 😭
i still need to learn a lot more about C#
Probably. You can put the same script on multiple objects
You'd need one script that handles the object turning on/off, then however many other scripts you'd need for the different ways that script can be told to turn on or off
imma see how im going to do that
but ill definetly keep your suggestions in the back of my mind
thank you!
yo dude, i just tried oyur suggestion and it worked! I had to ask chatgpt a couple of times but im learning from it
With the new input system, is it ok to verify player input in FixedUpdate?
I remember it wasn't ok with the old, but I guess this changed?
input is frame-based
the press and release will be true for 1 frame each
you can check if it's currently being held in FixedUpdate like you could before
What about read value?
you're better off using an event to assign a variable the read input value when the button is performed . . .
(which will happen per frame)
ty
Hello. I have a projectile that I move by using rb.AddForce() which ForceMode is an Impulse. When I it collides with a wall, there is a chance where the projectile can spawn an enemy when destroyed. The problem is that before the projectiles is destroyed it continues moving after it collides with the wall, so the enemy spawns outside the room (this happens sometimes). The Rigidbody has continuous collision detection.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CheeseProyectile : MonoBehaviour
{
public float speed;
private Rigidbody2D rb;
public Vector3 angle;
public GameObject cheeseEnemy;
public BoxCollider2D rataCollider;
void Start()
{
rb = GetComponent<Rigidbody2D>();
rb.AddForce(speed * angle, ForceMode2D.Impulse);
}
private void OnTriggerEnter2D(Collider2D col)
{
string colTag = col.gameObject.tag;
if (colTag == "Player" || colTag == "Room")
{
if (colTag == "Player")
{
col.gameObject.GetComponent<NaachoHeartSystem>().Damage(1);
Destroy(gameObject);
}
else if (Random.value < 0.2f)
{
GameObject queso = Instantiate(cheeseEnemy, transform.position, Quaternion.identity, transform.parent);
EnemyEnabler enemyEnabler = queso.GetComponent<EnemyEnabler>();
enemyEnabler.GetComponentsReferences();
enemyEnabler.SetComponents(true);
Physics2D.IgnoreCollision(queso.GetComponent<BoxCollider2D>(), rataCollider);
Destroy(gameObject);
}
Destroy(gameObject);
}
}
}
Since you're using a Trigger collider, it will have to partially pass through/overlap the wall before the collision is detected
to prevent this you would either:
- use a non-trigger and OnCollisionEnter2D
- do your own manual CircleCasting or RayCasting in FixedUpdate to detect the collision instead of using a callback
Also there is no reason to have Destroy(gameObject); three times in your code
once is sufficient
Ok, I will try that
That's true 😅
private IEnumerator WaitToMine()
{
Vector3Int tileTargettedPos = S_MiningControls.mouseCellPosition;
Tilemap map = S_TileManager.tilemap;
LiveTileData liveTileData = null;
//whilst left mouse button still held down
while (S_MiningControls.isMiningButtonDown)
{
//check if valid tile position
if (liveTileData == null)
{
//find current pos of mouse to see if we get a new tile
tileTargettedPos = S_MiningControls.mouseCellPosition;
if (CheckIfValidTile(tileTargettedPos))
{
liveTileData = S_TileManager.liveTileData[tileTargettedPos];
}
yield return null;
continue;
}
//check if our mouse moved
if (tileTargettedPos != S_MiningControls.mouseCellPosition)
{
//mouse position changed
//Set fade break sprite
StartCoroutine(UntouchedTileTimer(tileTargettedPos));
//set details
tileTargettedPos = S_MiningControls.mouseCellPosition;
liveTileData = null;
continue;
}
//mine
if(liveTileData.currentBreakTime >= liveTileData.maxBreakTime)
{
//break tile
TileBase tileMined = map.GetTile(tileTargettedPos);
AddMaterialToInventory(tileMined);
map.SetTile(tileTargettedPos, null);
//remove previous break sprite
S_TileManager.DeleteBreakSprite(tileTargettedPos);
//reset
liveTileData.isAlive = false;
liveTileData.currentBreakTime = 0;
liveTileData = null;
continue;
}
//BELOW THIS IS UPDATING STUFF, EVERYTHING IS IN ORDER
//timer
liveTileData.currentBreakTime += Time.deltaTime;
//Debug.Log(liveTileData.currentBreakTime + " / " + liveTileData.maxBreakTime);
//break sprite
float percentageMined = (liveTileData.currentBreakTime / liveTileData.maxBreakTime) * 100;
S_TileManager.SetBreakSprite(tileTargettedPos, percentageMined);
liveTileData.TouchTile();
yield return null;
}
if (CheckIfValidTile(tileTargettedPos))
{
StartCoroutine(UntouchedTileTimer(tileTargettedPos));
}
//nothing happened
yield return null;
}```
Why is this Coroutine taking longer than 2 seconds? I've set liveTileData.maxBreakTime to be 2 seconds.
The code is a coroutine that happens when the player holds their mouse over a tile like in terraria and mines it. However, hovering and breaking the tile takes longer than expected.
Does this mean my code is making it slow?
Or have I got an error somewhere ?
Nvm! My Timing in real life is off lol
it just felt wayyy longer than 2 seconds
hi guys i have this monobehavior script and im trying to link it to my object but its not allowing to drag and drop into it even though i have no compilation errors
this is the script
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
this
its too long i need nitro
Again, read the bot message. It tells you what to do with large code blocks.
here
Okay. And what are you trying to drag and drop?
im trying to drag and drop this bt communication script onto another class with has this object
here
but its not allowing me to
Take a screenshot of what you're actually dragging in
Ok, this is a script asset. You can't drag it in there. You can only drag instances of this script in there.
oh so i need to put it in the scene first?
i managed to drag and drop the script now but its still saying my object reference is not set to an instance of an object
Take a screenshot
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
You're likely overriding the variable value on line 53. Possibly with a null. Log the value before and after that line.
Ah, nevermind that. It's a difference variable
yea
This looks weird. I've never seen a syntax like that. What are you trying to do here?
drone => drone.ID
its a key selector used to specify that i want to create the binary tree by the drone's ID
my drone has many attributes and i want to create the binary tree based on its ID
Is that a lambda expression?🤔
yea
Share the whole error details.
Select the error and take a screenshot of the whole console
I see. So that's when the lambda is invoked. drone is likely being null there.
It's likely a value provided by the tree, so changing the name of the variable wouldn't really do anything
The drone code is unrelated. The value is provided from DroneBTCommunication
oh alright
I feel like you don't understand how your own code works, do you?
at line 32 in DroneBTCommunication what is the behavior you want if drone is null? or should drone ever be null?
int nodeKey = keySelector(node.drone); // node.drone is null
drone => drone.ID // results in null ref for drone passed to lambda at line 56 in Flock
just like dlich said
some parts yea im actually new to this cause i have to this for a course and im referencing some seniors work
but how could drone be null if i already gave it the arrays
oh wait
nvm
before i applied the method onto the object i partitioned the drones based on a pivot and stored them into arrays, this method works fine but how does it suddenly become null
once i remove line 56 the code works fine so the lessthanorequal array does exist and it contains my drone objects inside it
It feels really weird to me that you're using pretty complex syntax(that a beginner wouldn't know how to use), yet have difficulties debugging a null reference error.
i think I see what's happening
nevermind I was looking at the insertion and though the root assignment was messed up. one of the drones in the drone array must be null. I'd suggest moving the lessIndex++ out of the array access. ik in C that's supposed to happen after operations but that's making my spidey sense tingle.
my feeling is that the root node's drone is being assigned to null (a.k.a. drones[0] is null), so when the second node insertion is done, the KeySelector call on line 32 results in the null ref.
the call stack for the error always being at the root node despite drones being generated randomly makes me think this is a one off error, and the only place I think of a one off error happening is in partition drones.
i printed all of the values inside the partition array and i cant find any drones that could be null
Trying to make the health save from level to level, having the current health save as a int when the end point is reached, which I will then put in Player Prefs, I keep getting this error though
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
But it's pretty clear you never assigned instance
your code makes no attempt to do so
so you're getting a very typical NRE
actually is the stack trace for the error always the same? or was it just that one that happened to be at the root?
Okay, how do I assign an instance? and what is a NRE?
You assign variables in C# with =
instance is just the name of the variable you are trying to access when you get that error.
its always the same
@radiant glen see you are trying to access this Health.instance variable. Since that variable is null, you get an error. You cannot access a null reference or you get a NullReferenceException.
It is null because you never assigned it. You assign variables in C# with =
Okay, I see, so what do I need to assign then?
The variable
It seems like you're trying to do the singleton pattern
but you did not fully implement it
typically you would do something like this:
void Awake() {
instance = this;
}``` in the `Health` script
See how you can assign a variable with =
Instead of logging, I'd try to step through the code with a debugger, when the drone is being null. It should be a matter of seconds/minutes to figure out where the null is coming from.
how do i use the debugger in unity
its a bit of a setup process https://docs.unity3d.com/6000.0/Documentation/Manual/managed-code-debugging.html
it seems that the error is due to the root being null
because when i add a debug log to check if root is null before adding nodes it appears root is null and when i put it after the program just stops
so im guessing that's where the problem is
the root starts off as null, but is assigned with line 29 in DroneBTCommunication. However, the root's drone is null, which causes the error. The only way I can see the root's drone being null is if the first drone in the drones array is null. but if everything in the drones array is assigned then that's a headscratcher.
yea i figured out the error it was because when i was creating the node i didnt specify it to the drones inside the array it just used the local variable drones which is null, i fixed it by just adding this.drone
thank you guys for the help
they fooled us all lol
public LayerMask boxLayer;
public GameObject currentBox;
public Collider2D myCollider;
private void OnTriggerEnter2D(Collider2D other) {
Debug.Log("Something found");
if (other.gameObject.layer == boxLayer) {
Debug.Log("FoundBox");
currentBox = other.gameObject;
}
}
What do i miss here. The Layer in the BoxObject itself and the Layer in the boxLayer varible are correct, but it only prints "Something Found"
my porblem is player vertical camera jitter lag when falling. I fixed it by turning interpolate to none on my rigidbody but then it made my game feel horrible and the bullets are super laggy now. Is there anything else I can do to fix the jitter lag when falling without turning off interpolate ?
I can send my player movement or camera script
you are comparing a Layer with a LayerMask, they are 2 different things
if (Bla == x or y)
if (Bla == x || x)
What is the right sytax for that? if condition == Option 1 or Option 2. Is that even possible in c# ?
if (lastPositionPoint.transform.position == (new Vector3(1f,0f,0f)+transform.position || new Vector3(-1f,0f,0f)+transform.position))
if(Bla == x || Bla ==y)
//Boolean Expressions
bool first = Bla == x;
bool second = Bla == y;
//Conditional Statement
if(first || second)
...```
Hi, I've been losing my mind with this one since yesterday 😭
So basically, C# implementation of a file watcher is awful(and that's an understatement), and for some reason, gets triggered mutliple times when a file changes, and even detects incorrect events.
None of that would matter to me, I just need it to trigger when the file is changed, renamed or deleted, which it sort of does, but multiple times.
Issue is, when it triggers multiple times, and I am guessing here, it cancels the execution of a method it previously called?????
Trust me, I am as confused as you are probably.
I used rider to try and debug, it basically kept jumping all over the place 🤦♂️
So finally, I decided to see if it's me being majorly incompetent, and to my surprise, I wasn't.
Calling the exact same function the file change event calls results in flawless behavior and the expected result.
And due to debug logs I placed all throughout code, I was able to determine that execution of functions literally gets cancelled by another event trigger or something, I am losing my mind at this point.
I would really appreciate someone helping me debug this one 🥺
Here's the script responsible for dealing with config logic.
Lines of significance are:
9 - Calling the function on a keypress that assured me my logic worked just fine
110 - FSW setup and the function I am calling
137 - Function that stops midway through when called by a fsw, but works fine otherwise
if (bla is x or y)
{
}
Probably doesn't even work in current Unity
if (lastPositionPoint.transform.position is (Vector3.left * transform.position) or (-Vector3.left * transform.position))
{
}
Something like that
It might also be Vector3.forward
hi guys i have an object for controlling my UI but for some reason even after i link it to to the textinputfield and the button it dosent work
i cant use the input field or press the button
start != Start
still wont work
Add some logging
bump
the code runs its just that the buttons and input field cannot be clicked or used
screenshot your heirarchy
you do not have an EventSystem
do i link the UI object script onto that?
no, just add one to your scene
omg it works now tqqq
it would have been created when you added the Canvas, you must have deleted it
ohh alright mb thanks again
gotta love c# 9
I always wondered why when a canvas GameObject is automatically created they don't put the event system onto the same GameObject
Imagine having more than one UI canvas
true but to be fair the engine already detects if a event system is in the scene so it wouldn't add the event system to the new GameObject
Can't wait until they update their codebase so that I can suggest actual proper code
So you gonna disable the UI, cause its the main menu or whatever. what then?
Because it aplies to All canvases and you may have many
and what would happen when you disable the one canvas that happens to hold the event system?
bump
Has anyone knowledge about with DotTween. I look up Stack Overflow, but in my code is still a syntax error
transform.DOScale(new Vector3(0,0,0) ,1f).onComplete(() => Destroy(gameObject,0.1f));
it's a field, don't you need to assign to that
just a wild guess, onComplete() is an action and you gotta do onComplete => Destroy(gameObject, 0.1f); instead
wdym wild guess it says so right there
Still a syntax error
oh, I missed that completely 🤦♂️
I just saw a thing called onSomething and assumed it's an action.
but also that's not how you set an action
like i said, you need to assign to it
onComplete = () => Destroy(...);
my bad, I am tired, you should do what that guy suggested
this is invalid syntax; originally it was invalid semantically
That worked
a syntax error means c# can't read your code at all
what you had before was a semantic issue; it sees what you're trying to do but it's invalid
and yeah if this exists it would make more sense
actually seems like it just sets onComplete. so not sure what the benefit over the assignment is if it has the same behavior 
OnComplete seems to be documented, at least..?
DOTween lets you string a load of things together, so you want the () to be able to add another extension
transform.DOScale(new Vector3(0,0,0) ,1f).OnComplete(() => Destroy(gameObject));
``` This works, thank you for your help
why's onComplete accessible though 
You can also just do
bump
hey there! i'm following a tutorial on how to make a flappy bird game for my first project just i can't seem to figure out why the code doesn't work here is my code:
the problem is that for some reason when i touch the trigger it doesnt move my score up!
do you get the 'addc' log in the console?
any errors?
what debugging have you done?
100% this
Not just for readability
Stuff like events need a proper method reference and not a lambda if you want to unsubscribe, so get used to this instead
i've tried sending a msg to the debug when it touches but it doesnt work
im pretty sure that my addscore code works because i added score with a contextmenu
so your physics isn't setup correctly (colliders/ rigidbody/ etc) - go back through the tutorial where it tells you about adding this stuff and see what you missed
ahhhh
If 'addc' isn't being printed to console, OnTriggerEnter2D isn't being called.
Your sprite isn't "set to rigidbody"
Your player GameObject has a rigidbody component added
my bad i don't know how to call everything yet xP
my sprite has a rigidbody 2d for gravity and box collider 2d to collide and my pipe has a box collider 2d i don't get what i've done wrong i already checked the tutorial a vew times because i thought i did this wrong
show the inspectors of both objects
this is not a BoxCollider2D
fyi. If you want to do dev work you have to pay attention to every detail, no matter how small
but also, don't get hung up when you do make small mistakes - we all do it
i don't know if i'll become a dev i'm far far away from that i'm just trying to learn something instead of scrolling youtube all day haha
as soon as you touch a program like Unity what you are doing is dev work
hi guys, I currently have a script in a GameManager gameobject that calls a function whenever a value is added to a score. How can i detect whenever the function is called so that my ScoreUI (which is another gameobject) could call an animation? tysm
you can use an event . . .
alright will look into it im new in this lol
a script on your ScoreUI GameObject will subscribe to the event. this event is a field (class variable) created on the script attached to your GameManager. when the event is invoked, every method subscribed to it will execute . . .
yup i kind of figured it out just now, i just added the function onto the dropdown menu of the script event tab :)
tyty
nvm
Hey, how do I set a splines end point position through c#? I am trying to move and update how a spline is shaped at runtime, but I cant find the correct method or whatever
I guess you just have to add the position as last knot in the array of knots
hi guys, here I have script "points" attached to an event in which triggers the "triggerAnimation" function when called; however the animation seem to only play the first time the event is called and it doesn't work afterwards. The console message does continue to show up tho, anyone know what the possible problem would be? animator also provided here if it helps tyty
can it loop and maybe you need to reset the clip to play from start
if i enable loop time (as shown here) the animation would just keep repeating after the event was triggered once lol
and when i turn it off it's the situation i mentioned earlier :/
Again, did you revert it to start before playing?
It can't exit that state
If you don't loop it, it'll play once when you enter the state and then be there forever
Sorry i have a very basic Question, how to accesse indivual Compontes in a good/professional way? Even then they don't have a Script attached. What i used to far ```cs
// Option 1
private TextMeshPro moneyText;
private void Awake() {
moneyText = GameObject.FindGameObjectWithTag("MoneyText").GetComponent<TextMeshPro>();
}
//Option 2
public GameObject moneyTextObject; // Drag and drop Gameobject with editor
private TextMeshPro moneyText;
private void Awake() {
moneyText = moneyTextObject.GetComponent<TextMeshPro>();
Basically any method containing the word Find should be avoided at any cost
Option 3:
public TextMeshPro moneyText;``` drag and drop
and you're done
And the correct way is to just make moneyText public and drag it in and have no code at all
And option 4, which is really the most "professional" way generally:
[SerializeField] private TextMeshPro _moneyText;```
But i can't drag the Gameobject from the hierarchy into this public Field (i think i't because, the is a Componet of a GameObject)
No you can't drag it because it's a TextMeshProUGUI
not a TextMeshPro
If you drag an object that has that component onto a variable that holds a component, it will use the component
You should, in the future, just use TMP_Text instead of either of those
it works for both
Oh there not the same
no
Okay Thanks that's a really good tip
using UnityEngine;
public class World : MonoBehaviour
{
[SerializeField] private int _width = 10;
[SerializeField] private int _height = 10;
private Tile[,] _tiles;
private void Awake()
{
_tiles = new Tile[_width, _height];
}
private void Start()
{
for (int x = 0; x < _width; x++)
{
for (int y = 0; y < _height; y++)
{
GameObject tile = new GameObject();
tile.name = $"Tile ({x}, {y})";
tile.transform.position = new Vector2(x, y);
tile.AddComponent<Tile>();
tile.AddComponent<SpriteRenderer>();
}
}
}
}
is there a less performance-intensive way to instantiate a large number of gameobjects?
make them prefabs? so you already have the required components? shave off a few ms (if even that)
Would that make a virtual difference?
Like in terms of performance
try it and see, not likely anything substantial
Idk if Instantiate is better than New GameObject
cloning vs actual new() 🤷♂️
wtf constructing a whole new gameobject
Hello, a question, if I pass my code here, could you tell me what the error is about my character not jumping?

doing new GameObject() is worse because you have to manually add all the necessary components instead of using a prefab with everything all set up . . .
You could also try to create one object and instantiate it again in the loop without creating a prefab, I would guess prefabs are somehow optimized for that though, but as far as I know, nothing prevents you from cloning existing object with Instantiate too
It tells me I can't upload the code
👍
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
""cs
finaly
well, the error is that he does not jump, the character detects the ground and the jump key but does not jump, I checked the jump force, gabedad and mass but even changing those parameters he does not want to jump
read the bot message about Large Code
you skipped that part
also I dont see anywhere if you are debugging enSuelo value
Debug.Log("¿En suelo?: " + enSuelo);
what is the value here when you try jump ?
you should not have one Frame events such as KeyDown in PhysicsUpdate / FixedUpdate
srry, I'm not that familiar with these things and my level of English doesn't help much
chatgpt gone incognito
you dont know what Large Code means? its pretty common words..
we are not using rocket science terms
Hey, i have this error where i cannot make a reference to the camera fro some reason. Does anyone know why?
you mean drag n drop is not working?
you have your own class called Camera
yes
one of the object is scene and other is prefab?
yes
I doubt its their own class, it has camera icon
Is there another way to reference it?
pass the reference on spawn
How do i do that?
Ok, thanks!
with camera you probably get away with Camera.main property but this is probably better to learn properly from link above for other objects too
you can also keep the reference on the script that instantiates and after instatiating just add the reference to the prefab
yes thats what the link i sent suggests you do
oh yeah, i see it now, it is the cleanient soloution
yeah its a simple form of DI (dependency injection), very handy for other things too
direct injection
oh yeah
i think unity should provide an easier solution, people ask this thing alot.
in fact one of the most asked questions
mayn people start to do foolish things such as Find
I rather like the DI that .net apps have, idk games are a bit different
they do have things like ZenJect (third party though)
Hi in my game i can't look up, does someone knows how to fix it?
you should not be using Time.deltaTime calculations on mouse Inputs
thats why you set the sensitivity so high
mouse inputs are already framerate - independent
also your clamp is wrong , doing 90 90 when it should be -90/90
if you have top and bottom clamp variables, but why aren't you using them
if I'm running an if (audioSource.isPlaying == false) every frame but the audio source is set to loop, would that ever go through? is there a frame or moment between the loops where that is set to false or is that not something i need to worry about
wouldn't it just be easier to test this lol
You only need to set it false once if that's what you're asking
idk how id go about testing it considering it could very well miss it depending on how it works
i meant without setting it to false, just with loop enabled and playing normally
put a Debug.Log inside the if statement ?
if its just loop its probably still isPlaying until you call Stop() but dont take my word for it
thats what im assuming but wanted to make sure
audio looping isn't something independent. If the streamer isn't playing then the audio cannot play thus cannot loop
is that because it can only update isPlaying once a frame due to how the engine works
or is there a different reason
I would just test it and make sure it works how you expect in your specific use case
Does anyone know how do I fix this error?
mate . Configure your IDE first
What error
At the bottom of the screenshot
I don't see an error
not only do you need to configure your IDE as you've been instructed before, but you also should learn the difference between an error and a warning
yes but the warning you are looking at is not the error. configure your IDE
Okay, so look at your compile errors
You haven't shown any
open your console
oh
show us the error
So, that first one is an error. Which would be underlined if you configured 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
So do that, fix the thing that's glowing red, then try it
configure 👏 your 👏 IDE 👏
#archived-code-general message
this is non-negotiable. you have to configure it if you want to get help here.
also please look through the keycodes when done
https://docs.unity3d.com/ScriptReference/KeyCode.html
I can't find Editor Attaching
please read the instructions a bit more carefully
I'm a 2019 Visual Studio user
your point being?
Using 2019 Visual studio
do you think that Unity 2019 in the instructions you should be following is referring to Visual Studio 2019?
okay? wow they deleted their message, likely after realizing what i was trying to convey to them
I can't find IDE
wdym you can't find IDE? your ide is visual studio
Common7 Then
why are you looking for that? you already had visual studio selected in the dropdown according to the screenshot you posted then deleted
It's the thing you type code in
Your error is in another script. Read the error, make sure that prefab is assigned in the inspector.
I'm dumb
Visual Studio 2019 is your IDE, please follow the bot very carefully
ok
oh the error is gone from the screenshot, im just confused on why the debug keep saying Raycast did not hit anything.
UnityEngine.Debug:Log (object)
when i am right clicking on the tree and it should open the context menu
you raycast from the position of whatever object has this component in the direction that object is facing. it has nothing to do with where your mouse might be located
omg pls dont tell me
@dry jungle Should install 2022 from the Hub as in instructions there. It's faster and it will be properly setup out of the box. Will just have to switch to it in preferences.
if you want to raycast from the mouse then you need to use the camera to create a ray from the mouse's position and use that
pls dont tell me its just this.....
(it is)
i hate myself
I did it
i would love some help if anyone had some tips to give.
i've been trying to get a code up and running for a 3d platformer practice game, etc. But i'm having the worst kind of trouble with the rigidbody physics, and find my dude sliding all across the place on inclines, and i have no idea why it's happening. it's not even downslops, that could be debatably useful, but i'll slide horizontally off a ledge or something it's slightly inclined or enclosed by walls. i don't really understand why.
Please do not post screenshots of !code unless requested to do so
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
can you have multiple scripts on 1 object calling DDOL or should you split them up?
would it be like this? https://paste.ofcode.org/JX9igjuKNzL77umyXZQhju
ok so i tried it and when i right click on tree nothing is happening
It's still there
what is the value of interactionRange and how far is the tree from your camera?
You will need to provide full information for that. Controlling script, character object inspector, and maybe a video of the behavior.
why isn't the particle playing when i jump i've been trying to figure it out for the last 30 minutes even asked chat gpt but i might just be stupid
can i send you a screenshot?
i misread that hatebin link so hard
sure thing boss, we'll get to you on that
configuring your IDE wasn't meant to fix the error, it was meant to make it so that you see the error in your code
sure, i guess
OH i see what you mean
oh the interact range i have set to 20 and the camera angle is like this
Following any structured tutorial course in the first place that explains those things, like on Unity !Learn would've been preferable.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
its an isometric camera
does the tree have a collider on it and is your ray long enough to reach that collider?
read this and use the keycodes from it #💻┃code-beginner message
the correct keycodes
BYE
it has a mesh collider and idk how far the raycast is
well you're drawing the raycast, does it appear to be long enough to reach the tree? also is the tree's collider convex?
bye what? are you not going to fix the issue you had?
they came here for answers, not to read /s
that is an answer 🤷♂️
How can i rotate this sphere along the local red line?
yeah its convex is on but how can i check how far is the raycast? (btw im sorry im grabbing food from the kitchen)
rotate around its local y axis
using its transform
so you have these neat things called eyes that can physically see the line that you are already drawing in the scene
wait a minute that giant white line square box?
no, you are drawing a red line to represent the raycast. do you just not even know your own code?
im only know half of it...
let me guess, it's AI generated and you felt that wasn't important to disclose?
not that
well then if it isn't ai generated then you wrote the code and you wrote the comment that literally says "visualize the ray"
alr alr maybe i ask a little on how to create a contextmenu that all
how unoptimized is this code? I'm aware it's very, very messy. But in terms of performance, is it as bad?
That's everything. And I am learning through the tutorials, but I've come across through experimentation and wanted to know if it was salvageable.
cool so i don't help with ai generated code. good luck.
also give #📖┃code-of-conduct a read, particularly the part where it says not to post unverified ai responses in questions
you allocate an array every time you call this method. use the non allocating version of OverlapCircle
Use the profiler to find out.
But in general, you should be caching things that you use multiple times - especially when you're doing a GetComponent
alright, i'll do that, thank you!
i'm assuming there's documentation for caching. I'll check it out, thanks!
it's literally just storing it in a variable
usually the IDE asks if you want to use the nonalloc version
really? That's it?
do your distance check before the GetComponents
that's what caching is
yes, instead of calling GetComponent a bunch of times for the same component, call it once and store it in a variable and reuse that variable in each place you were initially calling GetComponent for that type
Physics objects use physics material that determines its behavior, like friction, there's also resting momentum as well. You should start with physics tutorials explaining those things.
hmm. well i have it so that when airborn the physics material switches to a frictionless version.
i've attached a more grounded material as well for the isgrounded state, but that didn't make any changes so i didn't commit to it.
so rather than
bool targetted = collision.gameObject.GetComponent<Target>().isTarget;
if (!targetted)
{
// Code
}
it would be more
bool targetted = collision.gameObject.GetComponent<Target>();
if (!targetted.isTarget)
{
// Code
}
right?
i'll give those tutorials a look t hough
well the variable type will need to change. but yes, then in the following lines where you call GetComponent<Target>() again, you would just use your targetted variable instead
yeah I see, thank you for all the help!
Debug that those states clear properly, otherwise it's a matter of configuring physics values like mass and friction to make sense for the current setup.
mass might be one of those elements. I haven't really messed with anything mass i don't think.
public void Update()
{
var quaternion = transform.localRotation;
quaternion.eulerAngles += rotation * Time.deltaTime;
transform.localRotation = quaternion;
}
``` Like this?
doesn't seem to work for me. looks like it still rotates along its global axis
just use transform.Rotate
okay, thanks
I am developing something very similar to this, https://pin.it/3kI90Vm07, but I have a concern. In my game the player can use multiple guns, all which could have different height size. When shooting, I want the bullets to move only in the y-plane towards the direction of the mouse. The problem is that the if the bullets come out of the muzzle of the gun, since the position of the muzzle of each gun can be in a different y-position, it makes the bullets not travel parallel to the shooting y-plane. This is because the gun is position so that its handle is set to an offset relative to the player's position. This makes the shooting in my game to not be consistent. How can I avoid this? Am I thinking in the wrong way?
How can I avoid this
Most shooters simply fire the projectile from the center of the camera
to avoid such a problem
Sometimes there's a particle effect that happens at the same time that appears to come from the gun itself
but it's an illusion
Sorry i just looked at the link and saw it's a topdown lol.
Similar things apply though
Are they all raycasts? Or are there slow moving projectiles?
They are raycasts
You probably want to raycast on a plane unless you need the y to go up and down
even without one , if you're using mouse as target direction you can just keep the Y pos the same height as your weapon/player/firepoint
like mousePosTarget.y = firepont.y , or something. Then calculate the dir
Then just do the raycast always from the same place. The visual projectiles (line renderers, particles, etc) can come from the gun muzzle to the place the raycast hit
Hey! I have a quick question how can I make a patrolling NPC hold a spot for a few seconds maybe add a animation before moving to the next waypoint?
@graceful walrus are you trying to do something like this?
Timer/Coroutine
could you give me a quick short example? of a timer / coroutine?
So i can base mine on that
IEnumerator Patrolling(float timeBetweenPatrolPoints)
{
while (true)
{
float t = 0;
while (t < timeBetweenPatrolPoints)
{
t += Time.deltaTime;
yield return null;
}
//go to next point
yield return null;
}
}```
ofc its an example, you can always make it randomize time and other stuff, a lot of Coroutine exmaples show the WaitForSeconds class but I personally don't like using it so i just manually do the timer as shown above
btw you can also use Update and use Time.time instead
Yes, but I don't need the y component for the bullets. The shooting should parallel to the y-plane
oh okay if you want specific height just assign the Y to whatever height you want
or don't rotate the X on the firepoint if you're doing that
you'd have to show more details of setup currently to have more specific
What you have is what I have minus the y component. But my concern is what to do if the guns are of different heights and so the bullets would be traveling in different y-planes, which would mean that the shooting plane changes based on the height of the gun. But this would make the shooting in my game inconsistent
so don't make the height based on the gun but a specific height you set
I know I could, but then wouldn't this make the bullets travel diagonally towards the mouse instead of horizontally?
Assuming the bullets come from the muzzle of the gun?
it depends how you are "pushing" the bullets, are they just raycasts? the mouse target y should be the same height as your origin Y pos
If they were raycasts then it would be understandable, but if they were not raycast, how could this be handled?
keep the two Ys consistent no ?
targetPos.y = firePointOrigin.y var dir = (targetPos - firePointOrigin).normalized
rb.velocity = dir * speed
Hmm, I think I am thinking about it the wrong way. But thank you anyway
sorry lol maybe show the current code and setup + whats happening right now, could probably be able to better understand the issue
I don't have the code for it just yet, it is just my analysis of the example I showed initially. In that example, their is only one weapon that is aligned with the shooting plane, but if the player was able to use multiple gun's and some of this gun's are bigger(for example, a rifle compared to a pistol), it would mean that the muzzle of the gun is higher and so the player would be shooting at a height depending of the gun's size, which it's not what I want
Hi, you've all probably have heard this a lot, but I'm new to Unity and am just completely new to any kind of programming software. Do you guys have any suggestions as to how to get started in learning how to use Unity and learning how to program? I appreciate any kind of advice! I'm completely new, so I don't know anything. Even a video tutorial that you think is very helpful will be much appreciated.
there are beginner c# courses pinned in this channel and the pathways on the unity !learn site are a good place to learn how to use the engine
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
hello every one i have an array of 6 buttons
and i want to change the position of each one
each time we press one of them but for some reason it show me that i didn't assigne any variables to my buttonsE array
the problem
why would height change with weapon change? either way you can still make the height of origin a fixed one
- !code 👇
- show the stack trace for the error
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Please post code that long to a link above
nah
Well you should debug or log your conditions for jumping
figure out which of them is not true while it should be
Yes, but you can still modify it?
and yet you should still log the relevant info instead of assuming other people will magically fix it for you without that useful information
well, guess theres no helping you then
its clearly not working code
lmao
i have, game dev to be precise 😄
if you think gpt is more useful than anyone here , you are sadly mistaken little bro
wrong layer on the floor?
alright, <@&502884371011731486>
not gonna be insulted here
no reason to be an ass towards other people <@&502884371011731486>
little bro the mods/admins can view deleted comments , so whatever.
they havent insulted you so there was no reason to do it
i told you to debug the code and you responded with "i wont do that", how are we supposed to help you then?
That's not how this works. Play nice.
Also this kind of attitude is not welcome here. You're in the wrong server otherwise.
!mute 1278821301619921048 1w Ok
whitefoomusic was muted.
should be seamless its the same editor
oh in that case 2021 should be just fine, depends what types of assets ofc but should be non-issue
2021, what an edit
actually we using 2022 lol
2 year gap 
Yeah, did that at work to test performance on the new version for an old project that bitterly needed an upgrade, no real breaking changes but urp custom shaders broke all over the place
but I have different projects on different versions, soo-
as long as you got VC test away!
Yes, we upgraded, yes, there were numerous things that needed fixing
Our URP custom shaders broke too
the most "breaking" change for me was all my Rigidbodies had to be switched from velocity to linearvelocity
he coming back for more
poor kid need a hug
I would have wanted to read this from start, but I just woke up lol
!ban 1278821301619921048 30 come back in 30 days when you've decided to be less of a fuckwit
whitefoomusic was banned.
Our custom shaders broke because the way keywords are resolved changed
We had to declare every keyword we were using in hlsl files at the root of every shader graph
i wish i could write non-shadergraph shaders 😐 another dev had to fix that stuff in the project
hmm wont you have to redo the shadergraphs?
nah shadergraphs are mostly fine as the nodes update too
or were you using hlsl? (I suck at both so probably not good idea to do all that myself)
If you're not using custom lighting then you probably won't have an issue
Dang I had a meeting and I missed some popcorn
Hey, I'm extremely new to Unity and C#. Could anyone help me with collision detection code for a prototype I'm working on? I think it should be really simple but I can't get it to detect the collision that makes the object play a sound.
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
(pay particular attention to that last part)
Thanks!
How are you supposed to test a clean save on mobile? It always fetches the previous save data on the phone, and there's no way to clear it out as far as I can tell? My game doesn't have a save slot system or 'new game' option
I tried to use PlayerPref to detect if it's the first time the game has been launched, and clear save data if so, but that only works one time and then it doesn't even work for subsequent builds
if you're saving data using playerprefs and want to clear all of the saved data, just make a button that calls PlayerPrefs.DeleteAll
Sure but I only want to do that the first time the game is played, and I don't know how to do that
well if it's the first time the game is played, then there won't be any saved keys
Well I just deleted the game on my phone and rebuilt it and the added playerpref ('GamePlayedBefore') was found.
{
Debug.Log("First Time Opened");
PlayerPrefs.SetInt("FirstTimeOpened", 1);
PlayerPrefs.Save();
if (Directory.Exists(_playerDataDirectory))
{
foreach (var file in Directory.GetFiles(_playerDataDirectory)) File.Delete(file);
Directory.Delete(_playerDataDirectory);
}
FindObjectOfType<LevelManager>(true).ResetAllLevelData();
}
else Debug.Log("Has Been Opened Before");```
well that's because it's not the first time it's being played. you already saved data. if you want to clear it out for testing, then just make a button that does that
yeah that's annoying to have to shoehorn a button in but ok
it's either that or you have to do more work by saving the current version number and making sure to increment that version number each time you want to clear it, and also make sure that code is removed for release so you don't fuck over your players for each update. plus having a button would allow your players to delete their own data if they so desired
done lol
Hello,
I have a little problem with camera + rigidbody fluidity. I used to use a character controller, but I decided to change it to have a physical interaction with some objects.
However, I can't get the same fluidity I had with the character controller...
I've activated interpolation, set the time step to 0.01, tried to separate my camera from my player, but nothing works...
It's really a problem of fluidity when I move forward at the same time as I turn the camera.
using System;
using UnityEditor;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
[SerializeField] private float sensitivity;
[SerializeField] private GameObject playerCamera;
private float _xRotation;
private float _yRotation;
private Vector3 PlayerMovementInput;
public Rigidbody _rigidbody;
public float speed;
private Vector3 moveVector;
private void Start()
{
_rigidbody.isKinematic = false;
_rigidbody.freezeRotation = true;
_rigidbody.interpolation = RigidbodyInterpolation.Interpolate;
}
private void Update()
{
var mouseY = Input.GetAxis("Mouse Y") * sensitivity;
var mouseX = Input.GetAxis("Mouse X") * sensitivity;
_xRotation -= mouseY;
_yRotation += mouseX;
_xRotation = Mathf.Clamp(_xRotation, -90f, 90f);
PlayerMovementInput = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
}
private void FixedUpdate()
{
MovePlayer();
RotateCamera();
}
private void RotateCamera()
{
transform.rotation = Quaternion.Euler(0, _yRotation, 0);
playerCamera.transform.localRotation = Quaternion.Euler(_xRotation, 0, 0);
}
private void MovePlayer()
{
moveVector = transform.TransformDirection(PlayerMovementInput) * speed;
_rigidbody.MovePosition(_rigidbody.position + moveVector * Time.fixedDeltaTime);
}
}
you're breaking interpolation by assigning the transform.rotation
hello i am making a finite state machine which depends on a tickManager. I want my states to change every tick. But currently, it doesn't work because it doesn't detect the boolean to true.
thank you for taking some of your time...
What do you mean by "Doesn't detect the boolean to true"
This is a lot of code to comb through for a "doesn't work" check, what's the specific problem? Which code is doing something you don't expect? What should it be doing instead?
MoveRotation may not be what you want, it likely won't feel very satisfying for players since it moves it to the desired rotation over time to the next physics update. you could probably get away with assigning the rigidbody.rotation, but i also recommend switching to cinemachine for the camera logic
So, I have a condition in my idle and move state wich make the state transition. I would like the state machine to change state every tick of my tickManager which speed can change
But currently it just doens’t detect the OnTick bool in the tickManager because it changes too fast from true to false
Share the !code in a bin site so it can be searched
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
https://hastebin.com/share/ibelepugok.csharp : TickManager
https://hastebin.com/share/bayabokapo.csharp : StateMachine
https://hastebin.com/share/exohajamaj.csharp : The Cube Class
https://hastebin.com/share/moyivotuco.csharp : State
https://hastebin.com/share/zalewolugi.csharp : IdleState
https://hastebin.com/share/balefacoka.csharp : MoveState
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I've changed to rigidnbody rotation, but it still doesn't run smoothly.
Hello, I need help to access some things of another script, I have this if :
if (lCollided.CompareTag(Tag)) {}
that return true and there is multiple object that I detect that have those tags, all the objects have the same script that contains a bool and a function that change the value of the bool. How can I call the function and get the value of the bool in my first script ?
Im not sure that Ive been clear, Im not the best english speaker
thx for your help
collision.gameObject.Getcomponent<YourScript>().bool_var
😄
perfect thank you !
hi i made thait but i can use using UnityEngine;
using UnityEngine.XR;
using UnityEngine.XR.Interaction.Toolkit;
public class ArmBasedLocomotion : MonoBehaviour
{
public XRController leftController; // Reference to the left controller
public XRController rightController; // Reference to the right controller
public float movementSpeed = 2f; // Movement speed
public Transform playerBody; // To rotate the player's body
private Vector2 leftInput, rightInput; // Input data from controllers
void Update()
{
// Get input from both controllers' joysticks (2D axis)
leftController.inputDevice.TryGetFeatureValue(CommonUsages.primary2DAxis, out leftInput);
rightController.inputDevice.TryGetFeatureValue(CommonUsages.primary2DAxis, out rightInput);
// Combine both controller inputs to create movement direction
Vector3 movement = new Vector3(leftInput.x + rightInput.x, 0, leftInput.y + rightInput.y) * movementSpeed * Time.deltaTime;
// Move the player in the direction of the joystick input
transform.Translate(movement);
// Optionally, rotate the player body based on input
if (leftInput.x != 0 || rightInput.x != 0)
{
// Rotate based on joystick movement (left or right)
float turnAmount = (leftInput.x + rightInput.x) * movementSpeed * Time.deltaTime;
playerBody.Rotate(0, turnAmount, 0);
}
}
}
it make a lot of lag
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Can you use the profiler? I don't see how this would cause lag.
It does on VR
And developing a gorilla tag fan game
That is the player movement
Well, I'd wrap it in an if and then go from there
if (leftController.inputDevice.TryGetFeatureValue(CommonUsages.primary2DAxis, out leftInput) ||
rightController.inputDevice.TryGetFeatureValue(CommonUsages.primary2DAxis, out rightInput))
can @nocturne parcel do you have a GorillaLocomotion temply it can use
do use use vr
i keep getting this error ArgumentException: Kernel 'KEyeHistogramClear' not found.
UnityEngine.Rendering.PostProcessing.LogHistogram.Generate (UnityEngine.Rendering.PostProcessing.PostProcessRenderContext context) (at ./Library/PackageCache/com.unity.postprocessing@3.4.0/PostProcessing/Runtime/Utils/LogHistogram.cs:25)
UnityEngine.Rendering.PostProcessing.PostProcessLayer.RenderBuiltins (UnityEngine.Rendering.PostProcessing.PostProcessRenderContext context, System.Boolean isFinalPass, System.Int32 releaseTargetAfterUse, System.Int32 eye) (at ./Library/PackageCache/com.unity.postprocessing@3.4.0/PostProcessing/Runtime/PostProcessLayer.cs:1254)
UnityEngine.Rendering.PostProcessing.PostProcessLayer.Render (UnityEngine.Rendering.PostProcessing.PostProcessRenderContext context) (at ./Library/PackageCache/com.unity.postprocessing@3.4.0/PostProcessing/Runtime/PostProcessLayer.cs:1091)
UnityEngine.Rendering.PostProcessing.PostProcessLayer.BuildCommandBuffers () (at ./Library/PackageCache/com.unity.postprocessing@3.4.0/PostProcessing/Runtime/PostProcessLayer.cs:699)
UnityEngine.Rendering.PostProcessing.PostProcessLayer.OnPreCull () (at ./Library/PackageCache/com.unity.postprocessing@3.4.0/PostProcessing/Runtime/PostProcessLayer.cs:493)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)
Hi, I am making a top down table tennis game and I use animationCurves to simulate the bouncing of the ball on the table. Everything was working fine until I added the check if the ball executed keyframe 3 of its animationCurve within the trigger area of the table, to credit points differently to each player. Now it doesn't work anymore, the animationCurve is not executed, the ServeMode is not activated either, the only thing that works are the physics between the players and the ball. script: https://hatebin.com/bkhoqnwfgc
- !code
- What does the profiler say is causing lag? What function?
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
no lag
then what is the question
Does Unity provide any global event/indication of game starting?
(Yes, RuntimeInitializeOnLoad is what I'm looking for 🦆)
I finished my movement finally. Feels goated. First project movement so it will be the first iteration of it's kind, but I feel I made accelerated steps in my understanding.
Is there anyway in code to put a child object in a specific slot, like if you wanted something to be specifically the second child.
Does anyone else have trouble downloading packages from git? I just get an error saying there was a problem. I got the error a ton of times in a row, restarted my computer and it worked. Now I’m getting the error again. Do I need to do something with my git installation?
yes, you can do that . . .
Trying to get this image behind the text any ideas how to do it? Cant seem to get it to work!
is there like a index you can set?
Move it forward in hierarchy
Thanks...
Worked?
you can set the sibling index of a Transform. just access the Transform component of the child you want to change and set its sibling index . . .
check the Tranform component in the Unity !docs for the method(s) . . .
Sorry I'm not sure which channel to ask this in but the localization package is making my project stuck on importing assets when playtesting
It's always after creating an Asset Table
I'm trying to use Localized Sprite Event
it sometimes works and it sometimes doesnt
literally no changes at all to script
it just doesnt work
I'm trying to pass a function as an argument but I cant get it to work, I tried using System.Action and using System.Action<>; like stack overflow said but it didn't work.
here is the function:
{
pointer = new PointerEventData(eventSystem);
pointer.position = Input.mousePosition;
//Create a list of Raycast Results
List<RaycastResult> results = new List<RaycastResult>();
//Raycast using the Graphics Raycaster and mouse click position
raycaster.Raycast(pointer, results);
//For every result returned, output the name of the GameObject on the Canvas hit by the Ray
foreach (var result in results)
{
if (result.gameObject.CompareTag("ItemPane"))
{
function(result.gameObject);
}
}
}```
what are you trying to do with the function? there are multiple syntax errors here
This code gets repeated across 5 functions in almost the same manner and I though that instead I just call the InteractWithItemPane() and pass the relevant function in.
Func<> returns a value . . .
ie ```public void UIOnMouseDoubleClick()
{
pointer = new PointerEventData(eventSystem);
pointer.position = Input.mousePosition;
//Create a list of Raycast Results
List<RaycastResult> results = new List<RaycastResult>();
//Raycast using the Graphics Raycaster and mouse click position
raycaster.Raycast(pointer, results);
//For every result returned, output the name of the GameObject on the Canvas hit by the Ray
foreach (var result in results)
{
if (result.gameObject.CompareTag("ItemPane"))
{
inventory.UseItemPane(result.gameObject);
}
}
}```
but you're not passing the function anywhere
oh I see what you want to do..
My end goal is to have something like InteractWithItemPane(SingleClick()) InteractWithItemPane(DoubleClick()) InteractWithItemPane(MouseUp()) etc
it's prolly just a syntax issue . . .
its a delegate right?
() is the invocation . . .
I'm wondering if this pathfinding algorithm is good
So theres obviously a cell grid, theres a moving node (you) and the target node (destination)
You check all open nodes in each cardinal direction from the moving node whos closest to the target node, and move the moving node there
And continue until you reach the target node
Is this a good pathfinding algorithm? and is there already a name for this? Its the simplest (i think) so I'm assuming its known
Is the one im describing still good even if its simple?
Or should I like... not use this one
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
just search the different pathfinding algos and get one that works for you, there is probably 99% chance you wont need to make your own at all
is there a way to make boxfill any faster? I created a 500x500 small grid and it already takes a while to fill
What is boxfill? 
tilemap.boxfill, im making something like terraria and first need to fill the world with tiles
i mean, that's 250000 tiles
not sure i'd call that small
public class CameraRotation : MonoBehaviour
{
public CinemachineVirtualCamera vcam;
public Transform target;
public void cameraMovement()
{
target.rotation = vcam.transform.rotation;
}
}
Hey all, I'm trying to get my cinemachine virtual camera to rotate the character body but it doesn't seem to work as simply as I thought it'd be. What's the alternative method to this?
Place a log before and after the rotation to see if the values are what you think they are.
They're pretty random values, I don't know how to make sense of it.
However, it seems the values change significantly when I move around rather than when I turn the camera which is weird?
Idk but maybe the cause is world coordination. Try making body child of camera.
And change localRotation
Have you changed rotation to localRotation of body?
public void cameraMovement()
{
target.localRotation = vcam.transform.localRotation;
}
should it be like that or target.rotation = vcam.transform.localrotation?
sorry i haven't quite got a handle on local vs global yet
Me too. Target.localRotation = vcam.transform.rotation
Im not advanced btw
doesn't want to rotate 😦
wait i don't think Cinemachines input provider when used for camera movement actually rotates the camera
because as i move it in game scene, the inspector rotation values stay 0 
how 2 make 2d objects clickable? only througth button conponent?
Let me try on my machine
Yep problem is input
did you get it to work?
i couldt find cinemachine, instead used camera.
ah okay, i started with normal camera but was told to use cinemachine
This is a coding channel #🖱️┃input-system
Or whatever this is
Literaly never seen this before
this is unity visual scripting
This channel is for code scripting. #763499475641172029
This is the channel you need then
k got it
Better chance of an answer there since there's likely not many people familiar with this here
hello everyone I have made this but the hp reduces drastically
Attention to the word "code" in code-beginner channel name 😉
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class HPBar : MonoBehaviour
{
[SerializeField] Image healthImage; // Reference to the Health image
public float maxHealth = 100f;
private float currentHealth;
void Start()
{
SetHP(maxHealth);
}
public void SetHP(float hp)
{
currentHealth = Mathf.Clamp(hp, 0, maxHealth); // Clamp health between 0 and maxHealth
UpdateHealthBar();
}
public void SetHPSmooth(float newHP)
{
StartCoroutine(UpdateHealthBarSmoothly(newHP));
}
private void UpdateHealthBar()
{
healthImage.fillAmount = currentHealth / maxHealth;
}
private IEnumerator UpdateHealthBarSmoothly(float newHP)
{
float oldHP = currentHealth;
currentHealth = Mathf.Clamp(newHP, 0, maxHealth);
float elapsed = 0f;
float duration = 0.5f; // Duration for smooth transition
while (elapsed < duration)
{
elapsed += Time.deltaTime;
float t = Mathf.SmoothStep(0, 1, elapsed / duration); // Smooth step for ease in/out
healthImage.fillAmount = Mathf.Lerp(oldHP / maxHealth, currentHealth / maxHealth, t);
yield return null;
}
healthImage.fillAmount = currentHealth / maxHealth; // Ensure the final value is set
}
}
hp bar script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BattleHud : MonoBehaviour
{
[SerializeField] Text nameText;
[SerializeField] Text levelText;
[SerializeField] HPBar hpBar;
Pokemon _pokemon;
public void SetData(Pokemon pokemon)
{
_pokemon = pokemon; // Assign _pokemon here
nameText.text = pokemon.Base.Name;
levelText.text = ":L " + pokemon.Level;
hpBar.SetHP((float)pokemon.HP / pokemon.MaxHp);
}
public void UpdateHP()
{
if (_pokemon == null)
{
Debug.LogError("Pokemon is null in UpdateHP! Ensure SetData is called before UpdateHP.");
return;
}
hpBar.SetHPSmooth((float)_pokemon.HP / _pokemon.MaxHp);
}
}
battlehud and battlesystem scripts
Please !code if you going for large code blocks
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
@astral falcon
Sorry for the ping
yeh, please dont do that
So, when is the code happening, thats not working as intended? whats the trace and how does it behave
Like when an attack is performed the health ui should update with the filled image function
Whats the function that should do this?
Hi, not sure if this is a right channel to post this q, but yeah, let me know if I should move it.
Would it be possible to get a system font, say by a name(should be possible w c# if I am not mistaken), somehow feed it to the tmp font asset creator, and spit out a usable font at runtime?
I don't need any code examples or anything, just your opinions on if it's is possible or not.
SetHp
Also twentacle, I said that I was gonna let you know if I fixed the issue, I have thanks to this server: #1306527853982253079
Thanks again for your previous help!
Apparently you can
https://discussions.unity.com/t/creating-tmp_fontasset-at-runtime/713578
For some reason VS didn't know that Unity's method like Awake, Update, OnCollider and so on will gets called by Unity, and mark them as Unused.
I've regenerate the project files a couple of times but it's useless.
Any advice to fix it?
Unity pcg
Wut?
screenshot your whole ide window
I think it's an issue with the latest VS patch.
Might be that the unity vs support package needs updating.
it's not "that big" issue just a little bit annoying. 😁
Yeah probably it's about Unity 6 and the lastest VS update.
I'd check the package manager for updates to the related package.
under "Get Tools and Features" there's no updates also in Package Manager, but It's a matter of time I guess.
In unity package manager...
Yea, nope 😁👍
I'll try to delete all the useless Unity's file, and reimport the project from scratch
What version is the package?
is coding your own pathfinding system considered "beginner"?
im having a hard time with doing it
No, I wouldn't say it is.
It can get pretty advanced depending on what you're trying to do.
i thought it was gonna be easier than this
but i might be close to finishing it
im not sure yet
Sounds contradictory
im still not sure how "good" the way im doing pathfinding is
its simple, i just set the position of the pathfinder to the neighbour who has the cheapest fcost
it sorta works
i mean it works amazing when there are no obstacles
goes to show that "simple" doesnt mean "good"
okay i think this part of my code is failing:
public List<Cell> GetNeighbouringCells() {
List<Cell> ret = new List<Cell>();
foreach (Cell cell in cells) {
if (cell.transform.position == transform.position) continue;
if (!cell.blocked) continue;
if (Vector3.Distance(cell.transform.position, transform.position) > 1.5f) continue;
cell.G = (int)(Vector3.Distance(cell.transform.position, transform.position) * 10);
cell.H = (int)(Vector3.Distance(cell.transform.position, destination.position) * 10);
cell.transform.name = $"{cell.F}";
ret.Add(cell);
}
return ret;
}```
oh i think i found the issue
yay i found the issue, and have successfully moved back to my original code
i just have to fix when it doesnt work around obstacles
Yes it is
The c# extension is broken, I reverted to the last update because of that
There's a workaround posted here:
https://developercommunity.visualstudio.com/t/Private-Unity-messages-incorrectly-marke/10779025
noticed this - at least it is a recognised bug, but seems MS often miss things with the plugin
It's a VS update issue, not so much the VS Unity package... they probably don't test VS updates with Unity things?
whats wrong? the instructor in the course wrote the same thing with no trouble
maybe finish typing the method and see?
doesnt log
Never look at errors while in the process of writing code. Your code was parsed and it just found an unfinished method because you didn't finish writing it
i usually mind the errors while writing but the tooltip for OnTriggerEnter didnt pop up while writing (even though it popped up in the course) so i got suspicious
Course probably not using VS Code so dont expect exactly the same behaviour
I suggest you switch to VS or Rider if VSCode can't autocomplete methods
oh i didnt realise that
This method should just have to be manually typed out
Especially since it's very specific
i feel like it would take a lot of effort to switch apps
i was told that vs code is like the best
You were probably told by somebody who has literally only used VSCode
Try VS or Rider and you will quickly figure out that this is likely the case
VSCode is the worst one. It's a nice general text editor but not a proper IDE for C# or Unity
https://pastebin.com/ELLASPuY : Cube Code.
https://pastebin.com/xFWkmjmz : TickManager Code.
Hello, i am trying to make a cube rolling game. For that, i made a tickmanager that sends an event each tick to the cube. On each tick, the cube changes state. I have an issue when the cube goes on a conveyor, i would like it to stop after hitting the ground again. i can't manage to do it. With all of what i tried, the cube just bugs out...
If you need more information just ask !
thank you for taking some of your time
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
what do you mean by "bugs out"
whats happening as opposed to whats supposed to happen?
can u clarify a bit
either the cube teleports to the next conveyor destination, either he just teleports back to the acutal conveyor
i tried casting a raycast inside of the DoActionConveyorMove() to see if it hits any conveyor but it doesn't seem to work
UnityException: Transform child out of bounds
UnitSelectionManager.TriggerSelectionIndicator (UnityEngine.GameObject unit, System.Boolean isVisible) (at Assets/UnitSelectionManager.cs:128)
UnitSelectionManager.SelectByClicking (UnityEngine.GameObject unit) (at Assets/UnitSelectionManager.cs:117)
UnitSelectionManager.Update () (at Assets/UnitSelectionManager.cs:53)
idk what i did wrong
the code behind my game is so messy but it works. I need to fix that mentality and actually refactor it but refactoring is incredibly boring. Any tips on making refactoring a little more entertaining, or do I just have to bite the bullet here?
The transform child out of bounds
The stacktrace has been so nice as to tell you where it happened. If you want help here I suggest you share the relevant !code inside UnitSelectionManager.cs.
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
yea homie imma honest idk what that means i assigend the child to the index of 1
ne of 0
can anyone help with my issue pls ?
did it works
Yes, thank you
ok
So, do you understand the concept of stacktraces?
erm no like a stack as in a paramater
From the bottom up it explains how it took the steps until the exception
So the last call before it broke was in Assets/UnitSelectionManager.cs:128
exception as in error?
Yes
erm so i clicked than it like broke
In your case this line is unit.transform.GetChild(0).gameObject.SetActive(isVisible);
after like a few clicks
Okay, so now you see the docs https://docs.unity3d.com/ScriptReference/Transform.GetChild.html
If the transform has no child, or the index argument has a value greater than the number of children then an error will be generated. In this case "Transform child out of bounds" error will be given. The number of children can be provided by childCount.
So one thing you can do is check if there's at least 1 child with childCount
But in your case there should always be a child I assume?
That's correct
But somehow the gameobject ends up with no child
If I were you, I would start logging the gameobject that comes in.
private void TriggerSelectionIndicator(GameObject unit, bool isVisible)
{
Debug.Log($"TriggerSelectionIndicator: {unit.childCount}", unit);
unit.transform.GetChild(0).gameObject.SetActive(isVisible);
}
Then, when the exception is thrown you press the log message that is logged in the console
When pressed, it navigates to the gameobject that was passed
Take a look and you will see it has no children inside
It's not supposed to go away, is it?
Don't debug by looking, debug with proof
Your proof is that log message that validates that it's actually using your gameobject
I updated the log message, use that instead
the child should uncheck after i unselect and that works but it just randomly bearks
breaks
thank you 🙏
its so good
it took me just 10 seconds to realise how good the tooltip is
do you understand
Wait until you dipped your toes into what rider assistant / github copilot offers you 😄 sometimes i feel like copilot is the only one that really understands me 😭 (/jk)
is github copilot free
the ''copilot'' word is enough for me to fall inlove with it
theres free ones out there. not sure about copilot.. i would assume its a free feature.. i use vscode and codeium..
theres something so helpful about being about to type out my variables and method names and have my assistant be like:
"oh, i see what ur trying to do here, let me save u some trouble and type out the basic boilerplate for ya"
copilot has a 30day free demo
there ya are ^
30d aint enough allat
🤤
its $10 per month after
it defaults everything to debug.log as of now. b/c thats what ive been doing lately..
but back when i was dealing w/ rigidbodies it was completing that.. and same w/ others
in love ❤️ lol
sometimes it does really neat things (only typed the function name here)
exactly!
other times... it does this
sooo good
rofl!! i never had it do that to me yet
pretty good about making lists and arrays
I don't mind hint/suggestions but auto complete will usually add exactly what I didnt want then proceed to add the namespace I have to clean up later
give me a sec while i wallrunjumpclimbsprint
tbh i havent had the best of luck using context..
like supposedly i can ask it a question and add my line number..
but most times it gets all generic on me..
oh copilots context chat is really good
i bet.. 😭 lol. that pay to win
found some really nasty to debug bugs by just asking copilot what it thinks could be an error source
company pays 😄
most useful thing that I found using it is formatting enums into bit flags
Just starting out on Unity, I added controller movement to my player character script, but it seems to have disabled my normal keyboard movement. What can I do to fix it?
how did you add it?
imo, this is the best feature AI has to offer.. Formatting and Refactoring
InputAction and then bound it to the left stick
Well, thats what it should do, take tedious tasks from us, sometimes that is writing simple functions tho 😄
do you have the new input system set as the default input method?
There's a default input method?
nah, id say copilot does some really neat stuff if it has enough context, ofcourse it cant write the base logic 😄
It's worth noting that I'm following one of the unity tutorials for a 2D adventure game
use google
yes use gogle, as gogle is the best search engine
Active Input Handling
stackoverflow about to become deprecated with the partnership with openAI. Is true through. Why would you want to continue using it nowadays if they're just going to sell your data haha
oh i wont let it write stuff that i dont understand, but ill gladly accept if it saves me 30s to type out a function 😄
I'm pretty sure I'm using the new input system
you mentioned the action map.. thast what that is .. hte new one
yeah for just writing functions and refactoring its neat
if its set to "Old" it wont work.. so use the new one or both
This is what I have atm
thats why i see it as 2edged sword for beginners, if you dont know if the AI is doing good or bad stuff things go sideways rather quick 😄
gotta give it the stank eye when you see it start to wander off the beaten path 😄
did you add another layout for the controller or did you add the controller input to your existing actions?
uhh what the hell is that 😄 can you show us your inputactions? should be in the project settings
you are settings the new position of the keys and then immediately override it with the controller value (which is 0 at that time)
check if the move vector is != zero
or add the move values together (+ normalize them so you are not double as fast if both go right for example)
I'm looking for these, but I can't find them in the project settings
mhh then first you should solve what i wrote above 😄
you would only use AI if at all (which I do not) as another hand to write simple things, nothing else as it is horrible with writing functioning code
I mean it can do it but 😬
did you generate a c# class?
it can write functioning code.. just that you don't know what function it'll have
should create a class you can use for ur inputs
If i see it right from his screenshot he is not even using an input asset, just straight up actions on his script 😄
i seen that.. i've never seen it slapped into a class like that..
yeah that's why its terrible, it also teaches you very bad habits like using find a thousand times 🥲
me neither, but seems to work somehow 😄 ¯_(ツ)_/¯
i thought there was two ways to do it..
- you generate the c# class and use that
- you use the player input component
it hurts seeing it happen
This is basically day 2 of gamedev with no coding experience, so I don't really know what the best methods are
I'm following a tutorial by unity right now, and these were the steps it gave me
well props to you for starting w/ the new input system
I'm sure I'll figure out more efficient methods as I keep learning
I think I did this?
Whatever I did it worked so thanks
if he is using unity 6 it should be the default selected
damn
i dont recommend learning the old input system when starting out with unity, it has gotten easier and its way more flexible
the only other package that they should finally include by default is Cinemachine
Damn
theres also a input debugger in the Window > Analysis menu
might be helpful when learning/ playing around w/ the new input system
Great, thanks!
https://pastebin.com/ELLASPuY : Cube Code.
https://pastebin.com/xFWkmjmz : TickManager Code.
Hello, i am trying to make a cube rolling game. For that, i made a tickmanager that sends an event each tick to the cube. On each tick, the cube changes state. I have an issue when the cube goes on a conveyor, i would like it to stop after hitting the ground again. i can't manage to do it. With all of what i tried, the cube just bugs out... either the cube teleports to the next conveyor destination, either he just teleports back to the acutal conveyor. tried casting a raycast inside of the DoActionConveyorMove() to see if it hits any conveyor but it doesn't seem to work
If you need more information just ask !
thank you for taking some of your time
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Ask a question if you have one
Show me the console when the exception happens
it does not tell anything
Except it will
ok should i cann you then bc i cant send the video
Win + Shift + S to screenshot portions of the screen
Full Console, w/ the last log
ok gimme 2 sec my dog is griefing
Hey guys! I'm completely new to game dev and C# (I work mainly on ML using Python). It's been about 3 days since I started, and I understand everything about the Unity Editor UI and the components system and everything, but I don't understand the coding part at all. Does anybody know any useful resources that helped you learn Unity and C# scripting.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
ooooh seems useful! thanks! I'll give it a try!
throwing myself at a pong project to learn unity, it works but is there a better way to do this?
private void FixedUpdate()
{
rb.MovePosition(rb.position + _moveDirection * Time.fixedDeltaTime);
if (transform.position.x < -8.5)
{
transform.position = new Vector2(-8.5f, transform.position.y);
_moveDirection.x *= -1;
}
else if (transform.position.x > 8.5)
{
transform.position = new Vector2(8.5f, transform.position.y);
_moveDirection.x *= -1;
}
else if (transform.position.y < -4.5)
{
transform.position = new Vector2(transform.position.x, -4.5f);
_moveDirection.y *= -1;
}
else if (transform.position.y > 4.5)
{
transform.position = new Vector2(transform.position.x, 4.5f);
_moveDirection.y *= -1;
}
}
currently letting the ball bounce off all walls just to test it out