#💻┃code-beginner
1 messages · Page 335 of 1
no but i want pixel by pixel
Your options are to make a new sprite with that new shape, or use 9 slicing or something: https://docs.unity3d.com/Manual/9SliceSprites.html
turn on point filtering for your texture in the texture import settings
i dont think it does anything with the players position or movement
You don't think?
it just moves the background, right?
public class ParallaxEffect : MonoBehaviour
{
public Transform cameraTransform;
public float parallaxFactor = 0.5f; // Adjust this value to control parallax effect strength
private Vector3 startPosition;
private float initialZ;
private void Start()
{
startPosition = transform.position;
initialZ = transform.position.z;
}
private void LateUpdate()
{
float parallaxOffsetX = (cameraTransform.position.x - startPosition.x) * parallaxFactor;
float parallaxOffsetY = (cameraTransform.position.y - startPosition.y) * parallaxFactor;
Vector2 parallaxOffset = new Vector2(parallaxOffsetX, parallaxOffsetY);
Vector3 newPosition = startPosition + new Vector3(parallaxOffset.x, parallaxOffset.y, 0);
transform.position = new Vector3(newPosition.x, newPosition.y, initialZ);
}
}
Well, it's your script, right?
And consider sending big code blocks using sites
my bad
yeah i was just a bit confused by the question lol
"The player is still jittering between pixels", you said. Where's the player script?
here
Could you also send it via site?
Since I have to download it to fully see it
ah right
did they remove the thing that shows ppl on mobile
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.
This is not the script I was referring to
What does it mean?
ah right, which script did you mean?
Player.
So what is [PlayerController](#💻┃code-beginner message) for then?
urrrrr
Moves the player?
Im not entirely sure what youre asking
oh my bad
i had the wrong script copied
thats the one for the paralax effect
You have said you don't have a specific player script. I have asked you what the PlayerController is for then. For controlling the enemies?
no its for controlling the player, sorry
i pasted the wrong script
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.
this should be the correct one
The things associated with the Rigidbody should be executed in FixedUpdate
In your case, you're changing the Rigidbody.velocity
Anyone know how i can fix the issue where my ui components are clipping through my 3d gameobjects?
So I should be using FixedUpdate at any point that i change rb.velocity?
It shouldn't happen unless your canvas is too near to the camera
Are you using a world-space canvas?
If you don't want it to be occluded by world-space objects, you should be using an overlay canvas
No a screen space - Overlay
I don't see you setting the transform there, so, yes, you should use FixedUpdate whenever you work with the Rigidbody. This includes Rigidbody.velocity
Then nothing in world space should be affecting it. It's drawn on top of everything else
alright, thank you
No there is no console channel, and yes that would be against the NDA.
Thank you!
Found out more after playing around its just text mesh pro objects doing that i can make a image and it will be renderd on top of it
I'm sorry, have you received the answer?
This is how the default Inspector is drawn, with the script's name at the start, and I don't really know whether you can somehow make the script's name go before the editor fields.
The code
Can i put stuff from UI where im struggling with buttons here? or would that be in another channel
nvm i got it already, thank you!
This isnt as much a scripting question as it is a logic question so Im not sure if this is the right place to ask, but say you have a grid made of hexagons with a character in the center hexagon. On every turn the player destroys a hexagon and the character will move one hexagon closer to the nearest outside piece. If no hexes are deleted at the beginning of the game, the character always reached an outside piece assuming the make the most logical move. So is there a way to determine how many pieces need to be destroyed so that the player always could win if they play perfectly. For example I know if you have a 7x7 grid and remove 14 pieces at the start, the player can win by destroying a max of 10 tiles. How can this be scaled to different size grids?
sorry, bad timing
haha all good thanks
@ PraetorBlue sorry for the ping. I've tried fixing the wall collision with your advice but I cant quite get it to work. Would you mind looking at my stuff again when you have time?
It's unclear to me who "the player" and "the character" are
and if those are different things
character is an ai enemy trying to reach the outside piece, player is the person playing that is destoying tiles trying to stop the enemy from reaching the outside. Sorry for confusion
what's a "7x7" grid mean in hexagons?
and are they trying to reach the 7th ring or the 8th ring?
For example I would consider the outside ring here the "4th ring" and the center piece is the "0th ring"
Anyway it is not clear to me that if the player removes one hex per turn, they could ever stop the character from reaching a particular ring at all.
Ah - that seems weirdly designed because the corners are further away than the sides
the sides are only 3 moves away. The corners are 4+
I suppose
anyway at each piece there are at least two possible moves bringing them closer to the outside, so destroying one hex at a time will never stop them
but I have working logic for this right now that if I destroy 14 tiles at the start of the game, the player can win everytime
yes exactly, so I would need to destroy tiles before the game starts
I mean couldn't you just destroy the 6 tiles surounding the start position and win?
no its randomly destroyed
like a certain number of tiles are randomly destroyed before the game start
Then what happens during the actual game?
is their any use or way of sorting values in a dictionary?
dictionaries are not ordered in the first place, so it doesn't make sense to "sort" them
the player destroys one tile per turn trying to prevent the enemy from escaping
sorting implies there is an order.
gotcha that's what i thought just wanted to be sure
I mean I guess it depends on which tiles are destroyed.
gonna use a List<> instead
If any 14 tiles are randomly destroyed before the game starts, the player always has a chance to win if they play correct
doesnt matter which ones
ive tested that
I don't think that's correct
If these are destroyed
it seems the player cannot win
that is not 14 tiles, but they could win that im pretty sure
very interesting game design
yeah I thought it would be an interesting start, ive already implemented the pathfinding logic for the enemy which was fun
I'm trying to make a third person over the shoulder camera but I'm struggling to get it to take into account the offsets. The line represents the direction its facing. here it should be looking straight ahead.
transform.rotation = Quaternion.LookRotation(lookDir - transform.position);
Debug.DrawRay(transform.position, transform.forward * 1000, Color.red);```
Am I doing something wrong here? The character itself is facing (0,**90**,0). The Target Transform is facing (-38,**85**,0)
Quaternion.LookRotation(lookDir - transform.position); This doens't make any sense
lookDir - transform.position < in fact this doesn't make any sense
i see
subtracting a position from a direction is ??
I figure I need the mid point between these two
what is this code meant to do
Its something like an over the shoulder camera. So the camera looks straight ahead of where it is but also accoutns for the pitch and offsets.
Im struggling with getting it to look at the proper spots atm
btw this:
var lookDir = _targetTransform.forward + (_targetTransform.right * _sideOffset) + (_targetTransform.up * _yOffset);
Can just be:
var lookDir = _targetTransform.TransformDirection(new Vector3(_sideOffset, _yOffset));```
Hi, would you mind quickly looking at my code again if you have time? Ive tried to do what you said regarding wall collision detection and teleporting the player to the wall when the player is on the wall but now the player cant move up and down, and gets stuck when holding the direction of the wall. https://pastebin.com/zQwewP1s
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.
ahh
er wait actually
you may have gotten me with that one, so there might be a few unwinnable scenarios
im honestly playing it in a different tab trying to win
Let's ignore the first line for a second
which should sort of work
ok
the second line should be:
transform.rotation = Quaternion.LookRotation(lookDir);```
But the real question is what do you want the "offset" to represent?
An angle? A position offset from something?
Its producing this
The offset just means how far off from the transform do you want to place the over the shoulder cam. Since its over the shoulder it would be something like Vector3(0,2,.2f) To the right of the player
I think if you truly are taking random positions, there are still unwinnable positions all the way up to 19 tiles
Unwinnable position with 19 tiles removed:
You'll have to be a bit smarter about this than just removing random tiles.
that isnt unwinnable
isn't it?
just removed the yellow middle right
but I see your point
I feel like unwinnable positions are rare enough that my method is fine for a 7x7
I just wouldnt know how it would change when I scale it
if you write an algorithm that detects an unwinnable position you can use that
and regenerate if you get one
to be fair half my legit solitaire games are unwinnable
but i wouldn't say it's a good thing
ah that would be smart, I would need to look into how to do that
lol
physics material 2d with no friction
it was working fine before, i just recently updated the code so that the player is teleported to be agaisnt the wall when a wall is detected
working other than always being 1 or 2 pixels away from the wall
oh in that case, physics material 2d with no friction
yeah i'm not going to try and read that code. if you want to share your !code do it correctly 👇
📃 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.
sorry, i just meant to demonstrate that it was working without being teleported to the wall
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.
is it possible for my class to have a constructor that can take 3 arguments but only NEEDS 1 argument to be filled when the object is created?
if you're going to use pastebin, at least have the courtesy of selecting the language so that there is syntax highlighting.
yes, your ctor can have optional parameters
Yes using optional parameters or multiple constructors with different # of params
thanks
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.
sorry, never used pastebin before
okay, and now have you bothered trying my suggestion. or are you just going to dump the code, expect me to read all of it and tell you some other solution to your issue?
using System.Collections.Generic;
using UnityEngine;
public class Ob : MonoBehaviour
{
Vector3 originalPos;
void Start()
{
originalPos = transform.position;
}
void Update()
{
if (transform.position.x < 52611)
{
transform.Translate(Vector3.right * 10 * Time.deltaTime);
}
else
{
transform.position = originalPos;
}
}
}
I have this object that is moving and when it passes a certain x point I want it to go back to the starting state and then start moving again.
sorry, i dont understand what your suggestion is
everything was working fine as shown in the video
physics material 2d with no friction
This code is not really working and I'd really appreciate it if someone could help me with it.
how do i add friction?
What isn't working about it
Is it not moving at all or is it not resetting
What are you trying to do?
well for starters i am saying to remove friction. by using a physics material 2d. that has no friction.
With a physics material
It moves but it keeps going no matter what then it falls of plane/ floor and down to eternity.
like a component attached to the player? i dont see anything named physics material 2d.
why are you trying to move your object 52000 units away from the origin? that is going to lead to some funky behavior
Have you googled it?
have you bothered googling it? or even looking at the components that are already on the player?
is singleton like i make a script named singleton, do the singleton loop thing and then whatever variables i make in that script are now acessable thru all scripts
Try logging transform.position.x, see what value it is when you're expecting it to be resetting
It is a huge environment and it is a train moving.
well that environment is too large. anything over 10k units away from the origin is going to experience floating point inaccuracy issues
transform.position.x < 52611 bruh
52611????
that should be basically the entire known universe in Unity terms
and i don't just mean weird issues with positioning. here's an example of how rendering is affected by being too far from the origin: https://www.reddit.com/r/Unity3D/comments/148ctmb/dont_forget_floating_origin_if_youre_working_with/
Probably but we worked on it on blender and moved it to unity and tbh nothing in unity makes sense (the coordiantes).
Many programs have different coordinates
Maya and blender have different ones haha
u can just scale it down
I will see what I can do about scalig it down. Anyways so the size is the problem tho right?
There is no fixing the problem if not scaling down
i mean, that's likely part of the problem
You could split the model and use floating origin
Loading pieces as you move closer to them, unloading when moving away
Possibly. Did you try logging the X value and seeing what it is when you're expecting it to turn around
how fast is this train to go from the origin to over 50k
floating origin is the other fix
Why are you showing this? And there are five listeners in the scene!?
You've cropped off the important bit of the error
Debug.Log("Resetting position: " + transform.position.x);
Why ping me with that?
Digi is the one who asked for it
I did this and nothing is showing.
Vertecies have CircleColliders and Edges have EdgeColliders
the errors you've shown have nothing to do with the code you previously showed
(but you should sitll fix them)
can you elaborate a little more?
Okay, what's Controller.cs line 110
basically every time you get to around 1000 or so away from the origin you move everything in the world back the other direction so then you're at 0,0 again
This is a huge project, that is not my part of the project so I have no clue tbh
So, why post it?
Well you should easily be able to access it
pretty sure they're trying to show that their log didn't print
Just thought I would show you everything
which we already knew
Then wherever you put the log didn't run? Not sure how that is useful without seeing the code where you added it
sure but "show don't tell" kinda thing
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
Vector3 originalPos;
void Start()
{
originalPos = transform.position;
}
void Update()
{
if (transform.position.x < 52611)
{
transform.Translate(Vector3.right * 10 * Time.deltaTime);
}
else
{
Debug.Log("Resetting position " + transform.position.x);
transform.position = originalPos; // Reset position
}
}
}
right we already knew this wasn't happening
because the object is NOT at x >= 52611
Should have gone in the top if
I said log the X position so you could see what it's actually at when you expect it to be greater than 52611. That'd mean logging it outside the condition
BTW this code makes me panic, deeply.
See how far it actually gets before it "falls off"
Seeing this tells me something somewhere has gone horribly wrong
and the project is in trouble
The blind are leading the blind in this project
By the way this is a less than not a greater than.
Yes I believe that's expected. They want to keep moving until they reach that point
It falls off at 100000 lol
what, you don't like seeing trains move in a completely straight line for 32 miles and expecting it to do so in just a few moments at only 10 meters per second?
Is that what your log outside the if says?
this is the original state:
I wasnt sure what you meant, apologies for my ignorance. Ive attached a physics material to the player with zero friction, but the issue persists. Does the material need to be on just the collider? The bounciness of the material is working, if thats at all relevant.
I mean my bigger fear here is that the entirety of the functional scene has been built somewhere around the vicinity of (51872, 65221, -4325)
has anyone else experienced their scene being way darker when they load it ingame
yes common problem, due to not baking your #archived-lighting
Why what?
there is no way your object is moving nearly 70 thousand meters at 10 meters per second in time for any logs to print.
that would take over an hour
Why are you starting the game at -17km, 4.6km, -17km
why not like
near the origin
Here just let me know what you're trying to do. I'll make it. Also be careful of floating point precision errors!
Why is this like this, it's beyond wild lol
but yeah to move 70km in a few seconds it will have to be travelling at orbital velocities.
That's the local position. What does the code say the absolute position is when it falls off
That's why you log
Oh, definitely. Just wondering where this "It was at 100,000" claim came from
indeed I'm wondering that myself. Along with where the magic number 52611 comes from
It is not really a game, but sure I will fix it but not right now since I'm gonna need to discuss it with other memebers
Anyway whenever you release "Kerbal Train Program" let me know so I can play it.
Also, They said it was from blender at that size, but it's scaled up to 600? What is this?
#💻┃code-beginner message
Edit: Sorry for the ping ultrasnow
why are you starting the simulation at that position then?
anyway Unity doesn't really support anything happening at more than about 1-2km away from the origin. This sounds like a perfect candidate for a floating origin system.
So I have this object, I want it to move and when it passes certain point I reset its position. Technically I am gonna do more than just reseting the position but that is what I am struggling with rn
The bare minimum here would be to actually log the position.
Debug.Log($"My x position is {transform.position.x}");```
No clue we made the blender design and randomly threw it in the unity.
Hey. I have a player and i have two animations made. One for Idle and one for Walking. How can i make it so when you start the game its the idle thats playing and not the walk? its connected correctly on the Animator. And i wanted to ask how can i make it so you move and play the correct animation?
So, right now, that is indeed what your code is doing.
There's just no way in hell it's travelled 73,000 meters at 10 meters per second in the amount of time you've said you've been saying you've seen the problem occurring
maybe be a little more thoughtful with what you're doing then.
This will start in the Idle animation when the game starts. It won't enter the Walk state until that condition is true
At which point it will stay there for as long as this object exists.
It walks at the start 💀 thats the thing i dont understand
What is the transition condition
That is true. That is why I am telling you guys I am so weirded out by unity coordinates. I have never really understood them. I can see my object moving and it never resets because it prolly never got to that point. I decided to take that point becaus I made an object and dragged to the limit I wanted to set and read the coordiante and said tada that is where I want the limit
There´s no transition candition yet.
I dont have any code. It just starts.
Okay so it transitions to walk as soon as Idle ends
and then never leaves walk
No one is active in that channel :(
Be patient
Tbh I'm not sure if it even was me or someone else but you are right I will be careful next time but anyways this is not really a big problem tho
The values you see in the inspector are local coordinates. They're relative to the parent object's position, rotation, and scale. transform.position is world position, which is relative to the origin point, which is 0, 0, 0 on an object with no parents.
alright for my enemy ai i have thought of a way to calculate all of the possible moves the enemy could make and weight them
but doesn't transform.position show me these
:(
That shows you the world position
guys it is now working
but how do i slow it down so it doesn't use a move every frame, but only when necessary?
some kind of coroutine waitunti maybe
anyways but doesn't this transform.position show me these:
because rn I set the limit for x =150 and it works like planned
The values you see in the inspector are local coordinates. They're relative to the parent object's position, rotation, and scale. transform.position is world position, which is relative to the origin point, which is 0, 0, 0 on an object with no parents.
transform.position = originalPos
I wanna start a little earlier than originalPos
what do i do?
What's going on, how come it says there's already a script named that when there isn't?
My guess would be that there is such a script and you forgot about it
This is a blank project
Weird even when I try to create a blank folder it's not working
Maybe I need to remake the project
Have you tried turning it off, then turning it back on?
Sorry?
Should i try and make my own inventory system or follow a tutorial
Always try.
i know following a tutorial would give me a more optimal script but i feel like i learn less doing so
No tutorial is gonna exactly fit your needs
Watch two or three tutorials and then afterwards try to make your own using bits and pieces as inspiration
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
private float timer = 0;
private float moveInterval = 30f;
private MeshRenderer meshRenderer;
Vector3 originalPos;
void Start()
{
meshRenderer = GetComponent<MeshRenderer>();
// originalPos = new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, gameObject.transform.position.z);
originalPos = transform.position;
}
void Update()
{
if (transform.position.x < 150)
{
transform.Translate(Vector3.right * 10 * Time.deltaTime);
}
else
{
timer += Time.deltaTime;
if (timer >= moveInterval)
{
transform.position = originalPos;
meshRenderer.enabled = true;
timer = 0f;
}
}
}
}
guys this is my code
@celest holly this is the optimal answer
okay thanks for the advice
just whenever i follow a tutorial i realise im just mindlessly copying
I wanted to set a 30 sec interval, as in when my object passes a certain point, I want to reset its position and make it wait 30 second before making it move. The problem here is that it is not really waiting 30 seconds.
i want tolearn these big systems so i dont have touse other peoples code
use an ienumerator instead
or an invoke
Ask chatgpt to write the script and then give you a coding lesson on how it works, and then quiz and grade you on it.
🤢
It's not ideal, but still better than a tutorial.
I'm sorry, I forgot where I was. Use Unity Muse, not ChatGPT.
lol. thats marginally better
but still.. hands on / docs / tutorials is the secret sauce
Anyone got any tip for this?
The issue is that after the first round of waiting 30 seocnds before movng.It never waits. It moves, resets and moves and resets.
you can post w/o trying to emphasize your message
we'll still respond
Markov Chain's gonna Markov Chain no matter what you name it
sounds like you probably have an exception being thrown from that code that you are ignoring
what is w/o?
Yeah
without
It says that there is no meshRendered attached etc.. but I saw online that this what I should do in order to control setting on and off the mesh.
Does the Train gameobject have a MeshRenderer on it
ya, probably missing entirely, or its missplaced
no. But I thought since it was a mesh it didn't need anything else.
A MeshRenderer is the component that renders a mesh
So do I have to create a meshrenderer component to be able to set on and off the mesh?
If you can see a mesh, there's a meshrenderer somewhere
Are you just trying to hide the mesh?
Wait I get it.
There is no mesh because
I have mulitple objects in the same folder with a shared script and collider
should I create a meshrenderer?
A MeshRenderer is a component that renders a mesh. You would create one if there's a mesh you want to render.
Just create a reference to the mesh renderer on the mesh.
how?
Usually with a public variable and then dragging in the object with the renderer
Public MeshRenderer mRenderer;
If you're wanting to learn, consider asking yourself if you're at a level where you can digest and learn what's being shown or just simply copying/pasting and being overwhelmed?
Truthfully, it's going to take time either way. The main difference would be if you learn better by doing it yourself or if you learn better by repetitively implementing the work of others. Doing both would probably the better choice where the order would be what you'd be comfortable with:
- learn and implement it yourself then observe how others have implemented it
- learn how others have implemented it then implement it yourself
Whichever is easier for you. The main goal would be to be learning and not simply accumulating unnecessary practices.
Can I not create a meshRenderer component for the entire folder containing my object that I wanna move? Let the code be the way it is?
How would you add a mesh renderer to a folder
not a folder I just don't know what they are called. I created an empty gameobject and put multiple partsof my object which together in the same heirarchy make one object.
At least now the error is gone and my program works but no meshs are being set on or off tho.
It looks like you are only turning the meshRenderer on. It's already on, so unless you are switching it off someplace else, there is no need to turn it on.
No. Use neither. No spam generator is good for learning
So you have multiple objects, some of which are child objects. If you want to toggle a MeshRenderer you need to reference the specific MeshRenderer you want to toggle.
but what if there are mutliple parts
Then you'd toggle multiple parts
private void generateGrid()
{
parentObject = new GameObject();
parentObject.name = "Tiles";
tiles = new Dictionary<Vector2, Tile>();
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
var spawnedTile = Instantiate(tile, new Vector3(x, y), Quaternion.identity);
TileSettings(spawnedTile, x, y);
if (x == 0 || y == 0 || x == width - 1 || y == height - 1)
{
// Outline
}
tiles[new Vector2(x, y)] = spawnedTile;
}
}
cameraObject.transform.position = new Vector3((float)width / 2 - 0.5f, (float)height / 2 - 0.5f, -10);
}
What can I do to give an outer outline to all the outer tiles? I figured changing the sprite wont work because then it would need to be rotated etc based on the side the tile is on. Is that the only way?
I want the whole thing to dissapear so I gotta create a variable for everything?
You could disable the parent object, which would also disable all child objects. A disabled game object also disables all of their components
Create an array, and then use find objects of type <gameobject> then use a var to check if it has a meshRenderer.
if u want to manipulate /modify something then yes it has to be a variable..
the code needs to know what ur talking about..
you can say.. disable the audiosource.. but the codes gonna ask which one
Absolutely do not do this
Or make a public gameobject array and manually fill it if you are afraid of code
u can change things directly.. but its still sort of a variable..
for example..
transform.position =
youre accessing the position property of the transform .. which is just a Vector3 variable
but the parent object like said is empty
it has no mesh
It does not matter, the child objects will get deactivated alongside the parent object, thus disabling their meshes and anything else there might be on them.
[SerializeField] GameObject objectToDisable;
private void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
objectToDisable.SetActive(false);
}
}```
but the partent is an empty gameobject
So what?
you can reference other objects
it has no mesh
Objects themselves can be disabled
doesn't have to be on the object running the script necessarily
So what?
Irrelevant
yeah but not using mesh rendered tho
Completely irrelevant
But I thought we were talking about meshes
You disable the OBJECT
so got confused a little
Which disables the children
Which disables the mesh renderers (and every component)
If you want to disable the meshes and keep everything else you could just recursively go through each child starting from the parent, check for a MeshRenderer and disable it.
Or just make a serialized array of MeshRenderers.
is the correct way to do what Jester was suggesting
like this: gameObject.SetActive(false)
That's disabling the object itself in it's entirety
Will also disable any components and children
Entire object alongside it's children
oops
how do i do it correctly then?
Depending on the end result you want, there are different ways
The only result I want is to make the object (and its children) invisble and then visible and toggle with it given if and else statements
You could make a new object that all of the meshes are children of, and then disable that. This way you just disable the meshes and not the main parent object
Do you care about any other components attached to that GameObject?
No? -> parentGameObject.SetActive(false);
Yes? -> Recursive or array
I have already done that
Okay, so then disable that parent object
That'll disable all of its children
How?
How do I handle the corners? I want the corners to have the outline on both sides.
public void SetOutline(bool left, bool right, bool top, bool bottom)
{
outlineOverlay.SetActive(true);
if (left)
{
outlineOverlay.transform.rotation = Quaternion.Euler(0, 0, 180);
}
else if (right)
{
outlineOverlay.transform.rotation = Quaternion.Euler(0, 0, 0);
}
else if (top)
{
outlineOverlay.transform.rotation = Quaternion.Euler(0, 0, 90);
}
else if (bottom)
{
outlineOverlay.transform.rotation = Quaternion.Euler(0, 0, -90);
}
}
this is what it looks like when i sink, it just isnt very clear in the last video as there wasnt alot of objects around
You should just use a 9-sliced sprite
i will take this whole death thing later. i have a problem is that i wanted to make a thing when you touch something, your power-up disappear and it works, but it only worked one time. when i take the power up and goes to the thing which removes your power-up agian, it doesn't work
https://gdl.space/aditihiker.cpp
Log collision and make sure you're changing the functions on the correct object
it'll not be true again.. unless u manually switch it to true somewhere else
ahh.. nvm i do see where u set it back to true..
try changing the conditional to if(_timer <= 0.0f)
why?
Two reasons:
- It makes sure that you're calling the function at all
- It makes sure that you're calling the function on the object you think it's on
So, you're colliding with an object named remove powerup?
yeah
Show the inspector for it
doesn't work
ahh sorry then, must be something else..
this is all
This doesn't have either of the tags you're checking for
Wait, this is the object the script is on
I asked you to log the thing this collided with
yeah,
i think it may be an issue with <Player2D>, can you show us this script?
i did
Okay, so remove power-up is colliding with remove powerup?
Why are you just logging the word "remove powerup". You should log collision to make sure you're hitting the object you are actually expecting to
That's why I said to log collision
public bool _isActive = true;
private float _timer = 2.0f;
private float _timerReset = 2.0f;
private void Update()
{
if(!_isActive && _timer > 0)
{
_timer -= Time.deltaTime;
if(_timer <= 0.0f)
{
_timer = _timerReset;
_isActive = true;
}
}
}
private void OnTriggerEnter(Collider other)
{
if(_isActive)
_isActive = false;
}
``` i tested w/ and reduced the timer to 2 seconds.. so it'd work faster.. but it **works**
@hushed hinge
are you properly setting !_suitOff to false when you powerup?
hmm... lemme check
i did log the word collision
Hello, my text is not entering the text field of my script
are you using text mesh pro? that uses a different type
yep
Why
that is what you told me to
No it is not
They said to log THE collision
like what you said here
Oh, yeah, log the VARIABLE collision
That is why it is in that font
Debug.Log(collision);
See the lack of quotation marks?
There's a bunch of options for some reason, but this one is what works for me:
using TMPro;
public TMP_Text textObject;
But better would be Debug.Log($"Collided with: {collision}");
oh
ty
There is a world type and a ui type. The one you did is the parent of both
oh, not it's working
i've tried all options and this one is the only one that worked for me for simple UI 🤷
Hello! I'm having a little bit of trouble using UnityWebRequest.Post to send raw body data to a api server on Unity 6. I'm i supposed to be using a different function? It seems like it doesn't like it when I give it any other data in the second string slot.
You mean as the second parameter? Wdym by "it doesn't like it"?
Yes, it is the parent of both types. So of course it will work no matter what.
You said it has multiple types "for some reason"
I explained the reason
either one of these will work for UI text..
Rider tells me its deprecated and unity auto corrects it to a UnityWebRequest.PostWwwForm
does anyone know how why when my tiimerboo is true the timers doesnt start adding up ?? and when it reaches 10 it should reset but that is not happening here``` if (timerboo == true)
{
if (timers < 10)
{
timers += 1;
Debug.Log(timers);
}
}
else
{
timers = 0;
timerboo = false;
}
When does it set timerboo to false, since the else statement only runs if timerboo is false
use debug statements to debug whats happening
turns out i can use a upload handler and just send the raw data through that
if (timerboo == true)
{
if (timers < 10)
{
timers += 1;
Debug.Log("Timers: " + timers);
}
else
{
Debug.Log("Timers reached 10");
}
}
else
{
timers = 0;
timerboo = false;
Debug.Log("Timerboo is false. Resetting timers.");
}```
it still for some reason does't run when the timerboo is true
Move the else statement after the if timers
Np
Alright I've been having issues with this walking animation for so long, but I'm having a multitude of problems with it
I want to solve at least one, so I would appreciate some insight on this issue at hand
Been trying to make the player jump, but we have a variable in which if you hold the spacebar, the player jumps higher, but it occasionally plays on that, and occasionally doesn't
What do I need to change here for the entire animation to play out both on a tall and short jump?
(I'm unsure what else I need to screenshot to have more info on the matter)
!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.
How do I make my missile that uses rb velocity look where its going
Its kinda facing one direction ALWAYS
Firing code
Missile code
It instantiates the missile and the shooting effect then deletes the shooting effect after 4s, switches to the next firepoint and repeat [This gives a left right effect]
It just gets the component, adds velocity, enables the rocket's thruster and keeps adding thrust in FixedUpdate
try setting transform.forward = _rb.velocity.normalized
Could also use something like lookAt (I forget the exact name) if you want it over time
For me that just makes it look at it without moving towards it
What like it keeps moving but sideways or?
Are you using AddForce?
Nah
Thank you good sir it has worked
Now back to struggling with guided missiles 😭
Sorry I’m on a phone so reading code kinda hard lol
Yeah all good
What’s rocketSpeed?
I've tried using LookAtConstraint & transform.LookAt but both I cant get the target because the missile a prefab
a float
Oki
Also sorry
How do I make something smoothly rotate towards an object or have a delay like its a realistic thing not instantly snapping?
I wanna say Quaternion.Lerp is the best, which may also fix your looking at things issue
there's also Vector3.RotateTowards()
Ok last thing
If im tryna get an object [a target] from a prefab how do I do that
Its kinda not in the game
Yeah I’ve found that to be funky sometimes but I’m probably just using it badly
Ill try both
GameObject.Instantiate
Uhhh idk what you’re trying
Say I want my missile to RotateTowards an object that isnt inside the prefab
depending on your use case, using quaternions might be better, for sure
How do you determine what object to target?
@random cave the thing that is responsible for instantiating the prefab should also set some kind of .target field on it
its a ball that I can move
what
ok ok listen
So it's always the same target?
I want my missile to look at a ball that is in the scene, since its not with the prefab I cant assign it or anything
Yes.
oh, if it's always the same target, that's easy. You could stick a tag on the target, and then use GameObject.FindWithTag() to find it in the missile's Start() method, for example.
!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.
FindWithTag or FindObjectOfType are probably best
OH YEAH TAGS
Pass it into the missile after instantiating or just make a static instance of it so that the missile get's it by itself
Hell no
how do I pass it into the missile after instantiating lol
Depends what specifically you’re looking for
Unity also pauses if I leave it empty
Is OfType in optimised? Yes. Is it very convenient for getting the component you need when optimisation isn’t an issue? Yes
By keeping a reference to the ball in the object that instantiates the missile, or again - via a static instance
wait a minute
You get the Missile component from what you instantiated (if you didn't instantiate the missile directly) and then you can access the public fields/properties/methods on it
That sounds smart
can I do
enter script name here.ball and I can use that?
if ball is a gameobject
But no
no harm in trying
that sounds close to the static field approach that @caesar is proposing.
You could, that's a static instance, most likely
Do static fields work in the inspector properly?
no
But passing it from the instantiating script has the benefit of easily expanding it to having several different targets for each missile if ever needed
yes it is from the instantiating script
downsides: they are also a bit of an issue if you want playmode hotreload to work, or if you want to disable domain reloading when entering/exiting playmode
the mother of the missile lmfao
So you’d be probably looking at a singleton for the static approach which I’d argue is less what this channel is aimed at. What caesar is actually saying is smart though
I prefer to dynamically get stuff at Start but I have a bad habit for that that I wouldn’t recommend if you’re aiming for super optimisation
what should I set for the radians delta [no idea what they do]
it's how much you want it to rotate. probably you want something * Time.deltaTime
Radians are kinda like degrees but in another unit, it’s the max rotation (I think?)
my game is extremely simple and phones acn probably run it
but its in fixed update lol
oh, then use fixedDeltaTime
Deltatime still works it will just not change tbf
Unless I’m misremembering how that works in fixed
Max magnitude iirc
I don’t remember how that one works
deltaTime in fixed update still just returns fixedDeltaTime
how do I make transform into a vector3
wait no im stupid
My brain thought transform was position for a second and confused why its not a vector3
Well now the moment of truth
anyone knows why input field doesnt work on mobile? The keyboard doesnt pop up to allow me to type
I dont want it to work because then I have to work on making guided bombs that GUIDE MOVING TARGETS [like bruh]
Well thats easy
Once you have them guide towards a stationary one you just change it to a moving one
Should be the same logic
Now that im thinking bout it
I just get the moving target, lookat its position and done
Exactly :3
Bro what that seems too simple
A lot of the time something that seems insanely complicated is just a small change
Does anyone know why my visual studio code just opens a blank screen with just the normal stuff at the top
(I have literally never used unity before this)
mb, it just seems weird that nobody has fixed it in years, cuz I saw that this issue has been around for a long time
I was ready to tear hair out over a bug someone found because I spent like 2 days fixing it, I’d swapped a - to a +
😭
Yeah sometimes it be like that
I’d help if I knew but I’ve not needed that yet so :/
If I give my game to someone to test they'd probably cry
Did you open it by opening it or by double clicking a cs file on Unity?
I double clicked on the file in unity like I saw an tutorial I'm watching
Can you post a pic of what VS looks like?
It's going to take maybe a minute or two because I have to get discord on my PC turned on
Oki
To be completely honest, showing your game to someone else for testing is one of the best things you could ever do
damn
^ I’m so glad I started testing this terms game early
The amount of bugs they notice is sometimes insane
My first and second term didn’t get much testing but this term I’m already on V0.5.2 and it’s week 3 I think?
Dang thats a lotta bugs
Yes and no
Lotta updates?
here it is
Sometimes an update is a bug fix spree and sometimes it’s just a hot fix or two
Can you all take this to DMs, this isn't a hangout channel.
Hhh been a while since I’ve had that, try ending the task in task manager and double clicking the file again
technically were talking about code lol but yee sure :3
sorry we will only yap bout code now
It still looks the exact same
I can’t help then sorry :/ hopefully someone else can
Do you know if there's anywhere I can look or try to find the way to fix this
!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
• Other/None
One is already enough, it's about quality, not quantity. Both are important but having a single person who'll check your game from start to finish is already better than doing it yourself, as the more you develop and test the more you tend to skip over some stuff and might not notice a fair amount of bugs.
Would this fix the issue? Looks like their IDE isn’t even opening the files properly rn
It may, yes

hey guys i need some help
i'm making a snake game in 2022lts version and i made a line to spawn the apple but it causing an error and idk how to fix
private Transform SpawnApple()
{
return Instantiate(applePrefab, new Vector3(Random.Range(-9, 9), Random.Range(-5, 5), 0, Quaternion.identity));
}
And what does the error tell you?
here's the example i'm following and the editor says that does not support 4 arguments
look a little closer at the example then your code
There is a small difference between yours and the example
i was wrinting wrong oh gods
Hi there,
my question is whether there is some way I have missed of making a gameObject a child of another object without affecting it’s local scale?
Example:
Object A has a scale of 1,1,1 and it is not a child of any object.
Object B has a scale of 1,1,0.5.
At runtime, Object A becomes a child of object B. Currently, object z suddenly changes scale along the Z axis to account for the 0.5 of it’s parent. Can I avoid this change in any way?
Has anyone had an issue where some animations don't fully listen to gravity while others do...? Basically 2 of my animations aren't fully contacting the tilemap but 1 of them has no problem working properly and I'm so confused lol
Now another problem has arisen, the game spawns the apple but when passing over it it does not destroy it even though it has the function
there's an overload for the SetParent method that will allow the object to change its local position, rotation, and scale to stay the same relative to world space. you can also tell it to not do that with that overload
!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.
how i use it?
did you read the bot message?
transform.position == appleInGame.position this is not a good way to determine if two objects are overlapping. this will only ever be true if the objects are in the same position, but just because they overlap doesn't mean that they are in the exact same position
how can i do it?
probably an overlap or something, or trigger?
you should start by going through the beginner courses on the unity !learn site. the pathways teach you all about the important stuff you'll need to understand, like collision detection
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
but in the video I'm watching he collides and "eats" the apple
I'm having trouble setting the position of an UI element that gets instantiated at runtime. Basically I spawn an object, then spawn the text on top of it. I can't get them to align. Are there any function helpers for this?
I'm thinking ScreenPointToLocalPointInRectangle but it doesn't seem to be working
can you link the video where they are comparing the positions for equality to check for an overlap?
you have to show a bit more of the setup, are you setting it to UI ? etc..
I'm parenting it to the canvas
the canvas is set to scale with screen size
overlay
That's the canvas and that's the Text that I'm instantiating
Basically I need to position the Text to an object that's also instantiated at runtime
So spawn object, spawn text. It's like one of those popups for health
an "object" is very vague
Faça o jogo SNAKE em menos de 20 minutos!
Preste atenção em tudo o que será compartilhando nessa aula. Você certamente utilizará todos os conceitos passados em seus próprios jogos.
✅Meu curso para iniciantes(https://criandomeujogo.com/cursoinicianteunity)
✅Ebook "5 dicas para começar na Unity"(https://criandomeujogo.com/ebook5dicasiniciarunity)...
everything is an object
GameObject
UI objects are also GameObjects
Gotcha
you mean like a world object?
A GameObject in world space yeah
oh have you tried just WorldToScreenpoint ?
wow that is not a very good tutorial. please go through the pathways on the unity learn site, they will teach you the concepts that you need to know
can u tell me why?
Let me try
its pretty bad
well there's the whole "comparing positions to check for an overlap" thing that is a truly god awful way of checking for collisions. what if the objects are 0.001 units away on a single axis? they are fully overlapped, but the positions are not the same so they don't count as overlapping with that terrible code
i have a problem, is that the twon different pencils in the background are like shown on both of the cameras even though each camera are supposed to be focues on the background which is supposed to follow the player
it works for all of the backgrounds
Would it be better for me to learn about colliders then?
well, ur gonna need to know about colliders for game dev anyway
its just 1 of many important parts
yes. and that's one of the many important concepts that the pathways on the unity learn site would teach you
So I think I better stop the project for now
Its better to follow the offical pathways to get a good grip on the basics included.
come back to it when you learn the proper tools/functions available to you
Yeah it's not working.
What I'm doing : Getting the world space object's transform. Using WorldToScreenPoint, then ScreenPointToLocalPointInRectangle, then parenting it.
why ScreenPointToLocalPointInRectangle.
just use screenpoint and set RectTransform anchorpos to it?
thanks
Yeah that seems to work better. I think I'm getting up the anchors of the text incorrectly
Would the canvas in the prefab cause issues or it's just temporary?
you might need to account for scale of canvas
makes sense, let me see
also just for shits n gigs try just setting transform.position maybe?
I'm trying to have my cannon change position based on where the mouse is, but it always chooses to the same angle when the mouse is clicked no matter its placement on the screen. Does anyone know what is causing this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CannonManager : MonoBehaviour
{
public GameObject cannonBallPrefab;
public Transform firePoint;
private Camera _cam;
private bool _pressingMouse = false;
private Vector3 _initialVelocity;
void Start()
{
_cam = Camera.main;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
_pressingMouse = true;
if (Input.GetMouseButtonUp(0))
{
_pressingMouse = false;
_Fire();
}
if (_pressingMouse)
{
// coordinate transform screen > world
Vector3 mousePos = _cam.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = 0;
// look at
transform.LookAt(mousePos);
}
}
private void _Fire()
{
// instantiate a cannon ball
GameObject cannonBall = Instantiate(cannonBallPrefab, firePoint.position, Quaternion.identity);
// apply some force
Rigidbody rb = cannonBall.GetComponent<Rigidbody>();
rb.AddForce(_initialVelocity, ForceMode.Impulse);
}
}
In which part of the code do I place the resolution into?
Got it to work, it was a problem with the scaler
that page is about how to correctly use a specific method that you are using in your code. take a guess at where you may need to change any of your code
It's not perfect, but close enough I guess for now
what it look like now
It works with constant pixel size, but it breaks with match screen size.
screen to screen size*
It kinda misaligns it a bit
If I change the ref resolution to 800 x 800 it works perfectly as well
But as soon as I go for a ref resolution of 16:9, it breaks again
at least it kinda works
did you try using the canvas scale?
Vector2 anchoredPosition = (screenPoint - centerPoint) / canvas.scaleFactor;```
This is what I got. I guess I should divide each component of the vector2? I'm a bit mind numb right now.
oh I was thinking something like
var canvasScale = canvas.scaleFactor * Vector2.one;
var scaledScreenPosition = new Vector2(screenPosition.x / canvasScale.x, screenPosition.y / canvasScale.y);```
but its prob not right
ah yeah
hi guys does anyone know how to add more than 1 submenu for create asset menu?
I applied a few different versions which make it move sure, but it doesnt work with the model of cannon i am using i think?
add a /
MyName/OtherName
Hi
Guys I want to create an score board and an starting screen for my ar game any tips?
huh? your issue was with ScreenToWorldPoint. i provided a resource that explained why ScreenToWorldPoint was returning the same position every time you used it as well as some solutions to get the position you desire. what part of that resource did you not understand?
use UI components
I tried this and it makes a sub menu of the sub menu 
huh?
And I had a problem with my hit box how to fix it
It's a Ballon shooting game
you need to be more specific with your questions
See #📖┃code-of-conduct
It is against the rules to dm people without permission
It is also not a good idea for YOU. Less eyes on the issue = less help
I'm sorry, I have been sick as a dog all weekend and I'm being a lot slower than usual, my bad
I made this change to my code:
if (_pressingMouse)
{
// Calculate the distance from the camera to the near clip plane
float distance = _cam.nearClipPlane;
// Transform screen coordinates to world coordinates using the distance
Vector3 mousePos = _cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance));
// Set z-coordinate to 0 to ensure the cannon aims at the same plane as the cannon itself
mousePos.z = 0;
// Look at the mouse position
transform.LookAt(mousePos);
}
}
this is AI generated code, isn't it
the code I originally sent is all me
the one i just sent was a fix AI sent me, yes
because i could not figure it out on my own
Oh my bad
Our professor suggested we use AI to figure out issues with code we were having for some reason haha
I know thats what i was thinking too but when he demonstrated it in class it worked for what he was doing so i guess thats why he suggested it 
he said if we could pinpoint the problem it would be helpful
Damn the proffs lazy
Paying thousands of dollars just for the proff to say use gtp
I wouldn't suggest using chatgpt, it's gonna block your progress
he's a great prof, he has been teaching us stuff all year, but if its anything outside of our understanding he said to use Unity forums and chatgpt to skim the code and find where the flaws may be
of course he said it is unreliable, because obviously, but there wasnt any other methods given if we were thinking outside the box from what was learned in class
we haven't learned any mouse location sensoring for the semester and i thought it would be much easier to apply but i was incorrect
One way to progress is to learn what words you should be using and learn to google or look for tutorials for it, another one that's very valuable is learning to read the documentation
It's weird to read the docs at first, but once you get into it it's really really useful
I've been watching a tutorial for a physics based cannon ive followed step by step at, which is helpful but everything works EXCEPT the cannon angling and im insure why
google the unity documentation
Unity documentation, learning the API. It doesn't fix all problems but it helps. If you know what class you want to use, you can read up on it and learn what it's able to do for you
Got something working yeee
whats the advantage of using abstract classes as opposed to interfaces?
Thats like asking whats the advantage of eating apples over oranges
i mean it seems similar
Abstract classes are mostly intended for providing default implementations. Interfaces only recently allowed for default implementations, so the gap has lessened, though there are still differences. Abstract classes can have fields, and I don't think interfaces can iirc?
If not changed recently, then yeah, only properties for interfaces
ah
But really it's a semantic thing, an abstract class means you expect a subclass to be that thing, but an interface expects an inheritor to implement that thing
oh i see
so with abstract theres a default but you can still change implementation in subclasses?
You use abstract classes when you have a concrete base functionality you want to inherit. Imagine a abstract mammal animal class. All mammals breath so you would implement that in the base class. Interface are when you have no concrete functionality but still provide a method signature.
oh that makes sense
You can if you define the implementation as virtual, you can have something that can not be changed as well
The thing is that categories suck and implementations can vary a ton, so it is apples v oranges, do what feels right to the scenario.
For example, reptiles also breathe, so why would mammal implement breathe. Would you move that to a subclass, or would that be an interface? 🤷 depends on what matters as far as the implementation is concerned
mmmm yea that makes sense
I need help with this error I've tried everything its impossible. Heres the script:
using UnityEngine;
using UnityEngine.EventSystems;
namespace HTC.UnityPlugin.Pointer3D
{
[RequireComponent(typeof(BaseMultiMethodRaycaster))]
public abstract class BaseRaycastMethod : MonoBehaviour, IRaycastMethod
{
public BaseMultiMethodRaycaster raycaster { get; private set; }
protected virtual void Awake()
{
raycaster = GetComponent<BaseMultiMethodRaycaster>();
raycaster.AddRaycastMethod(this);
}
protected virtual void OnEnable()
{
}
protected virtual void OnDisable()
{
}
protected virtual void OnDestroy()
{
raycaster.RemoveRaycastMethod(this);
}
public abstract void Raycast (BaseRaycaster module, Vector2 position, Camera eventCamera, List<RaycastResult> raycastResults);```
Is that the full script?
cuz if it is you're not closing the class, you're missing some }
Every { needs its corresponding }
It's the last line of what he copy pasted, might be something he just found cuz the error from what I see is pretty basic
This is a super basic question but is there a way to mass assign things in the unity editor? I have like hundreds of sprites that I need to assign to scriptable objects and I was wondering if there was a way to automate the process
Rather than dragging and dropping
mix in some onvalidation and then serialize it to a list
or ISerializable interface
oh, or do the menuitem attribute way as shown in the example
I have a 2D project and I want to rotate my player towards my pouse position but this seems to not work as intented can anyone help me? https://hatebin.com/tqqtrsrupe
there are a number of issues with that. firstly, that Input.mousePosition is in screen space not world space, which is where i assume your player is at so you need to convert that using the ScreenToWorld method on the Camera
then you're trying to rotate a position to another position and use that as a direction, that makes almost no sense at all. direction is computed with (endPosition - startPosition).normalized
and finally, Quaternion.LookRotation makes the Z axis point along the direction you pass to it. in 2D the Z axis is used for depth, it points in toward the screen. so when you make your object point its Z axis in the direction of the mouse it will rotate in a way you are not expecting. for 2d the "look" direction is typically either transform.up or transform.right depending on how your sprite is designed. you can just set the direction from the player to the mouse as the transform.up/right (whichever is its "forward" direction)
also why bother storing the mouse position in a field if you only use it in that one method?
I have a Character class, where I ended up putting all my character logic and visuals in, it's 600 lines of code.
But now I'm working with Cloud Save and json data to save my character
Like half the attributes are for visual stuff that don't need saving and a lot of the functions are too
I'd say what I need for saving/loading my character would probably be only 100-200 lines of code.
Any ideas how I would "fix" this?
Do I completely rework the class and separate it? How would I split it up?
Would it work just fine like it is now with a lot of the attributes not in json to Serialize/Deserialize it? Or would I have to write custom functions for this? I've been using JsonConvert.SerializeObject and DeserializeObject on a simple class and it works great.
Or is there some other way I don't even know of?
I have a Character object in my scene as well, but can't really think of a clean way to split it up. It just has the Character class script on it now.
!docs
ok so i tried learning unity 2 years ago but had to stop due to highschool. Now that i have graduated hs , i have started learning it again. I donot want to follow any yt tutorials as i cal easily fall into the "only watching tutorial" thing. My main problem is the scripting. I suck at scripting. I would love an advise.
scripting is the worst part for me
advise about what exactly
ask specific question
there is no general advise how to learn programming
Learn pure C# basics if you haven't yet as these will be necessary at all times when using Unity.
Don't want to watch youtube tutorials? Good. Go read a book or follow a course: w3schools is often recommended, as well as the course from Microsoft.
Once you're already past it, go through !learn to get a good grasp of all the Unity basics.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Yes thats exactly my question
I want to learn unity basics
But from where
I have done c# basics
The bot link right below my message
thankyou
You are missing multiple characters. I assume you do not have your !ide configured as it would point these out.
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Personally, I would split your serializable logic, and even your visual references if you want, if your able to offload the visual logic to another system your character can plug into, I think that may be helpful incase youd want other systems to reuse parts of your character (maybe for AI for example), but without much code change, you could have a reference to a serialized POCO to represent your data, and save/load that, you would have to write functions to save your specific data, though if you decide to build a generic save/load system, then youd only need to write those functions once, and any class can use it to save and load its specific data
I've been playing around with a ILoadable and ISaveable idea where I'd just have these custom methods in each class with their own initializer logic instead of sticking all that logic in the manager.
ChatGPT called it a DTO class
Data Transfer Object
Makes sense
Is it weird/bad to have these classes: Character (just the raw data), CharacterLogic, CharacterVisuals
But a lot of the logic is tied to the visuals
Say health changes, that's logic, but it also need to be redrawn on the canvas
Pretty easy to call a function in the other class, but it might become hard read the code really fast?
Sounds sensible to me tbh
I like using events for that kind of logic separation - your player could fire a "HealthChanged" event for example and pass the new HP value, your UI can subscribe to that event and update health bars, text objects, images, etc based on that health value as the param
I have some logic for changing player max health, on level up for example.
This needs to happen on my server (non-persistent, REST API) because we don't trust the client
The issue here is that when I sent a request to my server, the client has to wait for a reply to be able to update it's max health, which looks pretty bad
The logic could be really simple like maxhealth += 10 but if I decide to change it to 15 at some point, I would need to do it on both client & server, which I was strongly recommended against here.
So how do I fix this delay?
Feels overkill when it’s likely to be on the same object and you can just getcomponent
Thats also an option if your UI is on the same object as your player, then yeah you can just reference the object directly and cache the GetComponent in Start or something, though usually UI is a separate system to your player (if your trying to decouple a script)
I just have the UI elements as attributes on my CharacterVisuals script now
[SerializeField] private Slider healthBar;
Definitely not overkill, and its not like GetComponent is a separate or different solution to this. You can still GetComponent and then subscribe to events. Without using events, for example how would you know when to update your hp bar? You could check every frame but thats just not needed when events will literally notify you when to check and what the value is
usually if it's UI related then I'm subscribing to it
if hp changes -> UI needs to be notified then updated
It also helps if you're reusing scripts, the character script shouldnt know anything at all about the HUD (visuals). This lets you reuse the character script if you're making npcs or whatever, since you would handle their visuals differently
just playing around with networking it's gotten me to the point where I do need to split a lot of the visuals and the scripting data, but sometimes on smaller objects I feel like I could just handle it together in a single script
like, when you think about monobehaviours that are slots of an inventory, the correct way is for them to just have scripts that relay what's been clicked to the inventory, but if I'm lazy enough I'd just use those monos and make them into the actual data object too
another thing too is that you don't really need to share or reuse inventories (UIs) across different clients. To each their own so just integrating what's on the scene together with your data object can make sense.
Is there some way to make this work? I need exactly the same logic to increase strength, dexterity and intelligence
IncreaseStat(ref Character.Vitality, 1);
{
// Do not add stats if there are not enough points available
if (CheckNotEnoughStatPoints(amount))
return;
stat += amount;
Character.StatPoints -= amount;
CharacterVisuals.SetStatsUI();
SaveStats = true;
SaveStatsTimer = 0;
}```
you cant pass properties as ref or out
Is Vitality a property?
Likely you're only passing a copied value
I understand the error, I just don't know how to write this properly, without having to write a separate function for each stat
Make your stat a reference type
var vitality = Character.Vitality;
IncreaseStat(ref vitality, 1);
Character.Vitality = vitality;```
*use a reference type for stats
I'd still have to write that 4 times 😛
It's three lines...
In these situations I hate that C# doesn't allow you to pass variable names like PHP does
dont make it property
Character.Vitality.ModifyStat(1);
You're attempting to ref a value type like cs IncreaseStat(ref 5, 1);//error
Well, it's a different language. It's supposed to be used differently.
The return value from the property isn't the back field variable itself but a copy.
I don't understand
What exactly?
What you mean by that or how it would work?
You'd have a Stat class that has that method. Then you change the type of Vitality to that Stat class and there you go.
C# is an object oriented language, so that's the most natural way to do what you're trying to do with refs.
I'm just trying to find a way to turn this (example has 2, but I have 4) into one function
public void IncreaseStrength(int amount)
{
// Do not add stats if there are not enough points available
if (CheckNotEnoughStatPoints(amount))
return;
Character.Strength += amount;
Character.StatPoints -= amount;
CharacterVisuals.SetStatsUI();
SaveStats = true;
SaveStatsTimer = 0;
}
// Increase Dexterity
public void IncreaseDexterity(int amount)
{
// Do not add stats if there are not enough points available
if (CheckNotEnoughStatPoints(amount))
return;
Character.Dexterity += amount;
Character.StatPoints -= amount;
CharacterVisuals.SetStatsUI();
SaveStats = true;
SaveStatsTimer = 0;
}```
Adding a stat class sounds interesting
Or you cloud use a dictionary of <StatEnum, int> to store your stats. Then it would be as simple as Character.Stats[StatEnum.Vitality] += value;
Make a Dexterity struct and implements the + and - operators, and set the value that way
@topaz mortar
yeah this is all a bit too complicated for me lol
Structs work the same as a class if you assume it is just like your integer
But it takes some reading
I tried making a Stat class, but it doesn't fix my issue because there's still duplicate code in each function then, but it was interesting to learn this 🙂
yeah I think I'll just stick with duplicate code 😛 not a big deal
If you want an easy to read way, a struct is one of those ways
just looking for a better solution
just use field instead of property if no special logic needed to be encapsulated
Oh I didn’t think about UI, in which case yeah events makes sense
tried it but doesn't seem to change anything, same error as in my original post above
having github copilot auto-generate the duplicate code makes life easy 🙂
I think you have some bugs
yeah I moved Character to CharacterLogic & CharacterVisuals, nothing major, just gotta update all the references
and optimizing some stuff while I'm at it
//class that maps an enum, for all its entries, to a list of StatValues which when computed returns a final float value pertaining to that enum entry
public class Stats<E, T>
where E : Enum
where T : StatValue<E> //stat value is just wrapped values (percent, additive, ect) before being computed is added to our float dict value
{
//keep track of our instances of increased values
Dictionary<E, List<T>> statValueDict = new();
//values which are the result of all computed StatValues
Dictionary<E, float> valueDict = new();
public virtual bool AddStatValue(T statValue) { }
}
this is how I encapsulate my stats which is just a bit more logic than doing enum dict mapping
looks like something I might be able to understand in a year or two lol
I should really get a book on OOP and study it some more
it's just saying that an enum type, for all entires, have some stat they are specific to
If this is something you don't understand, why exactly are you generating your code using AI?
Sure it would help if you learned the process yourself?
I understand all the code I use 🙂
Hi there, i have added this models of a mannequin, and i wanted to add a feature to them but idk how i do it, i wanted to them to make a random audio, but only when i am a little far away, if i am to close then them don't make any sound, but if i am far from them, it would make a random audio.
Does anyone know how to add that feature?
Tbf VS started trying to guess what I’m typing and I never bothered to tell it to stop
if I'd use AI to generate something like that I would definitely figure out how it works
I might have to soon though because it’s getting less accurate
I've been programming for 20 years, but just never got to any of the more fancy/advanced stuff
github copilot is amazing
I use it mostly for speed, not to generate code I don't understand 😛
I don’t like to fully AI gen unless I’m completely stuck on learning a concept but so far VS has been not too bad at taking what I’m typing and extrapolating my goals based on names
what would you recommend to learn stuff like this?
to me this is far beyond the basics, I've been a professional web developer for 4 years and never came into contact with stuff like this
most of my colleagues barely understood what OOP means, well not sure if I'm very good at it either since starting working with Unity
or it might just be the difference between PHP & C#
Definitely
Php to me as someone that knows python, js and c# and has education in CS is a really bad “language” that basically tricks html into doing clever things (that’s my perception at least). Even JS which works on browsers tends to have a much more object oriented structure, but C# takes that much further than browser based stuff
PHP is just a lot easier than C#, at least how I remember it, it allows you to do so much more, most of which is probably just bad practice and why C# doesn't allow it
Eh it depends
I just use php because everything still uses php
I have no .net background so I can’t speak for that side of it but I would be in disbelief if php and html could make a game half as well as c# and Unity
I haven't used it for like 3 years now and started working with C# like 6 months ago
I refuse to lol
People say python syntax is weird but my mind is broken whenever I look at php
you can do some crazy shit with html these days html5 I think it is?
Oh for sure
I mean hell Unity can build to webgl
But that doesn’t make it optimal, especially from a developer side
programming for 20 years and don't understand generics?
what did you programm past these 20 years lol
Tbf generics don’t exist in other languages like python and js because they aren’t type safe so I only learned about them recently
I'm really bad with terminology as well, so I might understand "generics" but just not recognize the word
huh?
generics exists in python
and in js
Not if you don’t set a type for anything 
nope, never really used Generics, seen it a few times but never had a need for them
or I just never learned what they are so didn't recognize the need for them
They’re handy and powerful
i can't kinda understand how can you use something for 20 years
and don't want to improve
your skills
I’d recommend learning them or finding something online that uses them understand use case
i mean, if you can understand why list works in c# then that will probably help out
I like learning while doing, I hate theory
so if you can find a way to work around it without actually needing it, you kinda never learn stuff like that
weird approach but alright
Anyway, if anyone can recommend a book to teach me these "basics" I'd be very interested
If you want an example for something I first used them for, I made a script that emulated pythons random.choice. I could have made an interface for every type I needed or I could use a generic to allow it to handle a list of any type
generic in java/python/typescript is just static type checker iirc, the value is still got boxed
I have dyslexia, which makes it very hard for me to understand terminology like "generics" without actually using them
So I would only learn what they are and how to use them by actually using them myself
I learned programming in school and it never came up and then afterwards I never needed it, or maybe I did, but I just worked around it not knowing it
In a week I won't remember what "generics" are if someone would ask me
I can't even remember the difference between parameter and attribute lol
that's correct
well, actually it depends
depends if it's value or reference type
iirc value types are being boxed into their correspdoning wrapper types
One is in a method/function, the other is in a class
but there's no boxing for reference types
Parameters are limited to the context of its method, attributes are limited to the context of the whole class
Otherwise they function sumilaraly
this sentence for example has 0 meaning to me
but if you showed me the code I'm sure I would understand it
you don't know what's a value or reference type?
I probably do, I just don't recognize the terminology
yeah I know the difference, I just can't remember which one is which lol
dyslexia is fun 🙂
actually im not sure now, since generics are used for static type checking and do not affect runtime behavior, meaning there's no boxing at all 🤔
I have scriptable tiles I'm using for seasons. To save myself the time, I'm using a script to programatically update all the sprite references for each season. This works, at runtime and in the editor.
But when I restart the unity editor all of the references to the sprites just go blank, except for the first season which retains all the sprite refereneces. why is this happening? I'm saving the asset after I update sprite list, I'm saving the project
sprite references to other tiles that I added manually are also retained, but the first season's were all added programatically as well, so it makes no sense for this to be happening.
oh wait. i think i realize it's because when I added the first season to all these tiles it was added when the actual asset was created too
well, how do I make sure all these references are saved when updated programatically?
this is my code https://pastebin.com/k72T550X
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.
nvm im dumb i needed to mark it as dirty
one thing you could add in you foreach loop is
EditorUtility.SetDirty(customTile);
i like how i come to that realization as soon as you reply-
Not sure if this helps, but look into: SetDirty(itemSO), AssetDatabase.SaveAssets(); and AssetDatabase.Refresh();
It worked for me for saving SO's from script
thanks yall
lol, that's the way it often goes
I need help, I'm a beginner and I want to save the open chests so I can't open them again and they stay open, the problem is that I change scenes in the game so it gets complicated because they go by index and if I change scenes and the I try to load it goes crazy, I don't know if I explain myself, can anyone think of how to do it? Could I just destroy the gameObject with tag chest that I just opened and it disappears? The problem with deleting it would be that if I start the game again it would be there again, right??? please help
I have no problem sharing between scenes, the problem is that the chests are a list with an index, because I am not going to pass chest to chest, that is where I have the problem, a list between scenes with an index number, when in a scene the 012, in the next one it should be 234, but it is still 012, so the order does not work