#๐ปโcode-beginner
1 messages ยท Page 123 of 1
your exp should look if the playre entered it
then get playerstat component and increase the xp
ah. i wanna make the player look if exp enter it . thinking i can get better performance cuz exp will be instanciated alot during run time
please pool them
okay
feel like im asking about everything lol. but i feel like there are so many way of doing thing if i go on my own and pick the wrong one without knowing a better way of doing it i might stick with it for a very long time
i have a player GameObject that has tons of children, and some of those children have children of their own and even those have children of their own and so on, so how do i loop through everything under that player object?
Recursive loop
void LoopThroughChildren(Transform parent)
{
foreach(Transform child in parent)
{
// Do stuff on child...
// ...
LoopThroughChildren(child);
}
}
99.99% of the processing there is in the GetChild and the SetActive, the rest is virtually irrelevant, a very odd way of writing for statements though
Yeah, see the foreach way of looping children in caesar's example above @uneven current
thanks :)
Does anyone have an idea how I can get rid of the deadzone that is present when using a G29 steering wheel in Unity?
The x value seems to have the deadzone while the sticks Vec2 is fine. Cant really use the Vec2 value though since using the left pedal changes that value as well.
Just wondering, does the magnitude of the vector Physics2D.gravity matter? i.e. does it have an influence on the actual gravity felt?
Isn't that something you can test in 10 seconds?
ok im sorry
Is there a way to put a colour in a collider ?
Idk if that makes sense
Just wanted to add like a colour on the collider
for debugging the pick up range
no code question, collider "color" is global setting iirc
you can set it somewhere in preference or project setting -> gizmos or physics
forgot completely
Hi again. I've been watching and following CodeMonkeys series on Pathfinding using unity DOTS. And I've gotten to a point where he's started talking about the entity component system. However I've installed the package and it looks like its in experimental. Should I be using the ECS or not?
void Start(){
renderer.material.color = Color.black;
}
void OnMouseEnter(){
renderer.material.color = Color.red;
}
void OnMouseExit() {
renderer.material.color = Color.black;
}
Is this how you usually code a "hovering selection" in a menu
Hi guys, I have a code for NPCs that does this: when player distance to NPC is 2.5 or lower and I press E while my mouse is over player it should start conversation but for some reason it wont detect my mouse over NPC object, it detects it in weird angles like when I look at his feet from angle it will detect that my mouse is over him and I dont know how to fix it. This is my dialogueManager script that goes on NPC: https://hastebin.com/share/nujupeqaqi.csharp and this is NPC script in which I put all dialogues: https://hastebin.com/share/qoqurapugo.csharp
Is this a question?
If yes, then yes. This will work if you have a collider.
Consider not repeating the same parts of code more than 1 time. It's bad for the readability.
There's no question mark.
void Start(){
OnMouseExit();
}
```you can do this
It won't make sense if they add additional behavior, which don't need in Start(), to OnMouseExit() method
I think the problem is in your question, there is no such thing as 'usually', if it works for you it's good
depend
it guarantees the initial state at least the same as the state after mouse exit
Yep. They'll have to make sure this happens.
Anyway, creating a method like Hover(Color value) will be great too
private void Hover(Color value) =>
renderer.material.color = value;
How would I be able to set a transform rotation to look at another target based on speed value rather than lerp?** Using a constant rotation speed.**
RotateTowards probably
Did you even look that up on google
Based on the results i only saw lerp slerp and transform.look at i was looking to get teh actual rotation
Thanks I'll try this
It doesnt seem to be working, the parameters do change but the transform itself isnt.
{
Vector3 lookDirection = _target.position - transform.position;
// The step size is equal to speed times frame time.
var step = _speed * Time.deltaTime;
var rot = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(lookDirection), step);
Debug.Log(rot);
// Rotate our transform a step closer to the target's.
transform.rotation = rot;
}```
Looks like I have to use https://docs.unity3d.com/ScriptReference/Vector3.RotateTowards.html
This seems to do the trick
My Debug.DrawLine() doesnt show up even after enabling gizmos and double checking if the position is correct im not sure why im not seeing it
public class Grid
{
private int width;
private int height;
private float cellSize;
private int[,] gridArray;
public Grid(int width, int height, float cellSize)
{
this.width = width;
this.height = height;
gridArray = new int[width, height];
for (int x = 0; x < gridArray.GetLength(0); x++)
{
for (int y = 0; y< gridArray.GetLength(1); y++)
{
Debug.DrawLine(GetWorldPosition(x, y), GetWorldPosition(x, y + 1), Color.red, 10000f);
Debug.DrawLine(GetWorldPosition(x, y), GetWorldPosition(x + 1, y), Color.red, 10000f);
}
}
Debug.DrawLine(GetWorldPosition(0, height), GetWorldPosition(width, height), Color.red, 10000f);
Debug.DrawLine(GetWorldPosition(width, 0), GetWorldPosition(width, height), Color.red, 10000f);
}
private Vector3 GetWorldPosition(int x, int y)
{
return new Vector3(x, y, 0) * cellSize;
}
}
public class GridManager : MonoBehaviour
{
private void Start()
{
Grid grid = new Grid(200, 180, 16f);
}
}
You did Quaternion.Euler(lookdirection)
That's nonsense
You're supposed to use Quaternion.LookRotation
That's why it wasn't working
ahh
the docs just show it plugging in two rotations
so if you've two transforms then wouldnt that suffice?
How to make a personalized cursor that works both with mouse and gamepad with unity input system? I need the ability to hover, exiting hover etc like old input system
you still probably want to use IHandler interfaces
^^ this + switch the Input module to new system
any idea why i have this error when following along with a tutorial. the debug menu doesnt show an error
i think i followed exactly but i just can't seem to see what I missed
oh well im not setting cellSize therefore its 0....
its not or it would underline red
Case sensitivity
did you save ? are you sure thats not older error
The error is showing it lowercase
yep double checked that
i'll do another case check, and even check the other code to see if something has the wrong case
well there is nothing on line 101 so clearly they don't match
even the lines above have the correct case
just show where you declare voxelData in the script
yes but the error you showed , the lines number of error doesn't line up to anything. That's why I'm asking if you cleared all older messages in console
it wont let me clear it
correct me if I'm wrong when I refer to vector I can either refer to vector1(x), vector2(x, y), or vector3(x, y, z)
no
right?
vector1 is not a thing, you just use 1 axis
so just vector for the x right
there is no such thing a vector or Vector
so theres only 2 vectors. Vector2 and Vector3
3, you forgot Vector4
double click it, where does it take you? also show the definition for voxelData
Vector3 direction;
float xDir = direction.x;
The components of a Vector are float
(Unless you use the int variety of Vector)
dont tell me about vector 4 Im just going off what ruby's adventur is telling me
Is Tuple<int, int> effectively the same as (int x, int y) but with better syntax?
it takes me all the way to the end of my code
yesterday i didnt get the vector system so im just try to see if im right which i see im dead wrong

Vectors are just structs of floats (or int)
They just hold 2, 3, or 4 values
still dont get it
a simple example please
Vector2 has two floats
Vector3 has three floats
oh okay
so the way i describe it from the x, y, z, vector2 can only refer to two of those and vector 3 and refer to 3 of those and I don't want to really know about Vector4
Vector2 = (x, y)
Vector3 = (x, y, z)
Vector4 = (x, y, z, w)
what the heck is w
No profanity, please
you need to start reading and understanding the docs
https://docs.unity3d.com/ScriptReference/Vector3.html
im autistic i have a hard time understanding text
You don't really need Vector4. I still haven't used it yet too.
mk, will do
Anyway, you surely have to understand that Vector2 is for 2D coordinates, and Vector3 for 3D
yes i get it i just wanted to see if my thought was correct and so far its yes
So you'll use Vector2 when you have to scale a UI image that obviously doesn't have a z value
fuck that
Is it even allowed on the server?
yeah
then ok
as long as you're not insulting someone
thought you can get banned for this.
im doing ruby's adventure and its's only my first 30 minutes into it
I'm surpised it still works
Haven't you done those 5 projects on Unity learn?
Please Note: We are aware that this project is getting older - Ruby's 2D Adventure will be updated in 2023.
its 2024
wassup
havent touch it
i have this error now
just dm me them please
thats more like it
well this is a runtime error
somethin on line 19 is Null
I will do it here instead.
https://learn.unity.com/pathway/junior-programmer
That's a cool pathway. Just 12 weeks
I needed 3 days though
so I think you can do it till tomorrow
hmmm, i've got a feeling my 5 days off is just nothing but get up a 4 spend 16 hours doing code and repeat
i don't see anything obvious to me thats on line 19 or any above it
There's no active gameobject with a name "world".
you can serialize the variable and drag and drop the component to it
didn't find a game object called World
then you can delete that line
So accessing its component gives you an error.
cause he never made one yet, though somehow he got his to play
"he"?
I see. Well, it's a mistake
you followed wrong or tutorial is shite
i coulda sworn i changed that already
both is good
:doubt
but its more than i could do on my own
at least it makes some sense, most tutorials don't explain what code does
GameObject.Find is one of the worst u can use
Well, they just follow a tutorial.
Ain't their mistake
im aware
if you just need that component at least do FindObjectOfType<World>()
i forgot a capital that i thought I fixed
so after that you still thing strings are good to use ?
unless they have lots of worlds
Well, how would you find a GameObject by its name or tag without strings?
if you're using string to find something you have poor designs
mind as well use javascript
Yes, I'm usually using strings to find something
then you're doing it wrong ๐คทโโ๏ธ
I don't.
I either serialize it or find it (when using prefabs)
if you say so. Talk to me about it when you learn a bit more on reflection
i'm only on part 4 of a tutorial series that has 30+ and the github code looks cleaned up by a lot. so at this point this is what its gonna be untill i get to the point where he optimizes everything
I mean follow it , just be aware that thereare better ways you later must learn
Does anyone know why my webgl build is not working. I tried turning off the compression format and then building. I'm unsure what the errors mean.
not sure this is a code question
which button are you pressing? afaik you need a local server to use WebGL locally
oh what channel would be appropriate?
ik, i've just never done anything like this before. if it were a webpage theres no way id do it this way.
#๐โweb prob
or #๐ปโunity-talk at most
web design is where my knowlege ends, no idea how to apply any of that to unity and video games
web dev is completely different indeed. The closest you get to real coding if you're using TS and doing Server side JS
is this question for me?
it was yes.
i went into build and run
and clicked on the build and run button there
is this what you were asking?
There's no point checking anything other than the indicated file and line number
yes. afaik that should spool up a local server from unity.
did it oppen localhost link?
i dont think so
when i did that
errors popped up
sorry lets move it to #๐โweb
ill take a screenshot
do you guy have any playlist for me to watch to start coding using unity dont mistake me, im not new to coding i used to code in Lua for around half a year.but switching to unity is completely new to me any suggestion?
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
is that a playlist or a long article
they are playlists
oh ok thank gonna look into it
how i can create textmeshpro text gameobject fully from script?
unity does not like something because its taken 2 minutes to complete a domain
look at the text mesh pro editor source code and see how they do it
why.. just use a prefab
i did it i MADE MOVEMENT!
just realized that i did the y movement differently form the guide, i made a separate vector 2 variable for the vertical
sometimes errors can happen on the lines above, thats like rule one of debugging
yay congrats
Pretty much only when your error is a missing semicolon or curly brace
so in this guide it's asking me to do a tile map but there are more options thine the guide is saying.
anyone nows how tiles work
It was not the case here, that is rarely the case actually. I recommend listening to Praetor, they know a LOT.
which one is Praetor?
ah nvm i see
never knew that missing curly braces or semi colons is what caused errors in lines above. thats definitely something i felt any of my courses should have explained rather than saying its a hard and fast rule( it actually has a reason)
not a code question. Also everything is there they are just moved
yea i know
btw Rule 1 of debugging is 'Read and understand the error message', Rule 2 is 'Don't make assumptions'
its usually the second half of rule one that gets me. because sometimes i don't know what the error is asking me to change
that is why google exists
indeed, in my day we just had books
hey guys while coding, i noticed code completion on tutorial videos, I use Jetbrains, JetRider to open scripts, how do i make my code completion work while typing? its enabled, but it doesn't suggest things that other tutorial videos show.
Depends on the code editor, but the post below has all the links
!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
how to check the directory of builded files in game?
what are builded files in game?
when you make a build, you choose the output directory
followed instructions, still not working ๐ฆ
What code editor are you using?
restarting unity usually helps
and choose your ide in external tools
also can hit regenerate project files
then edit->open c# project
ahh I need to know where the .exe files and MonoBleedingEdge things when the builded Game runs
I'm not struggled at finding builded games in real life
you specify the directory when you make a build
unless i dont understand what do you mean
You select the build output directory yourself
๐ I really sucks at explain
when you click "Build" you specif in which folder the build should be made
you can find .exe and all files in that folder
I mean when User plays the game, the launched game should know where the program itself located
use google translate, your english is almost impossible to understand
no idea what do you mean
when the user launches the game
it depends where he installed it
or unpacked or whatever
he can launch it from desktop for example
When a user runs a built game, I want to know where the executed .exe file is located.
Environment.CurrentDirectory
could we possibly call and see my screen? ๐ฆ
Just tell us what code editor you're using
no
Jetrider?
There's no need to restart if you did all the steps
Jet Brains Rider
and it will work
thats not related
Do you get errors underlined directly in the code?
Code completion is context-aware, which means if you type stuff somewhere where not many completions are available (like outside of a class), you won't get many suggestions
well i see on a tutorial video
of him typing
using UnityEngine
and it shows up
mine doesnt
#๐ปโcode-beginner message
This WILL make it show up, if you carefully follow each step without skipping a single word
Hi I'm trying to use the new input system, I found two ways to check whether the sprint Key is pressed or no:
Keyboard.current.leftShiftKey.isPressed
sprintAction.triggered
Is there a difference between each one of these? I suppose the second one will check all the mapped keys in the sprint action, such as leftShift, the gamepad key for sprinting, etc.. Or no?
The first one does not use your Input Actions Asset
Ah okay
The second one does. It's better to use the second one if you have any processors or triggers on the action
You was right, I was to stubborn and missed a crucial step
sorry
I don't have it doing anything as I already have a movement script, and am replacing the old input system keys like .GetKey and .GetAxis, with the new keys from input actions asset. But I'll keep it this in mind, thanks!
The New Input System is more event-driven, so it's quite the amount of changes required in your code if you want to use it as such
But you can absolutely use it with action.triggered for a poll-based input like the old one
Understood, though I'm supposed to add all the inputs right? like move, look, jump etc.
nah i just think visual studio hates me at this point ๐
Yep in your Input Actions Asset. Then you can assign multiple inputs (keys, joysticks) to the same binding, and refer to it in the code very explicitly since the name is the same as the one you set in the Asset.
So you have something like actions.Vehicle.Steer instead of some Input.GetAxis("Horizontal")
No worries! Glad it's working!
Great, that's exactly what I understood from a video. Thanks for your time.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class RoomManager : MonoBehaviourPunCallbacks
{
void Start()
{
Debug.Log("Connecting...");
PhotonNetwork.ConnectUsingSettings();
}
public override void OnConnectedToMaster;
{
base.OnConnectedToMaster()
Debug.Log("Connected to Sevrer");
PhotonNetwork.JoinLobby();
}
}
...
followed a tutorial, did everything just as they did, but my launcher just wont work, gives me many errors, as i know this is probably something simple to fix, im pretty new to coding so for me i dont really know.
!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.
New to coding, do not start with multiplayer games
Also, if you're following a tutorial.. and there's works, but yours doesn't .. you missed something/ did something wrong
well i have made fps games before, many, now i am trying a multiplayer
have you developed and shipped a complete singleplayer game yet? otherwise you aint even close to ready
You have a syntax error, it should be pointed out in your code directly by a red underline
yeah, i am trying to fox my visual studio but I can't my visual studio does not even show that stuff, or highlights / finish the words. I know there was a fix but i forgot how to get to it.
It was like IED or smth
Make sure it is configured properly by reading through the !IDE guide below again
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
okey dokey
is Awake on ScriptableObject will execute when game will run?
When the SO is loaded
but will it run on game execure
didn't have visual studio in my preferences, but visual studio still opened when I try to open a c# script, don't know for sure, but maybe it fixed it.
When the SO is loaded
The IDE opening when you double-click a script in Unity is normal. If you set it in the preferences, then a project file was generated and it will likely be fixed
thank you very mmuch, if i need help I will reach out to you. Have a wonderful day..
If that's not the case, look at the Solution Explorer in VS and make sure the projects are there and are loaded
ok
There should be at least one named "Assembly-CSharp". If it says "incompatible" or "unloaded" for it, right-click and select "Reload with dependencies"
yup that fixed it
thank you so much man.
your a life saver
now ima tryi t again :)
What does XR mean?
Extended Reality. It just encompasses VR, AR, MR.
Ty
void Start()
{
grid = new GameObject("PlayerGrid").AddComponent<Grid>();
}
does someone know why 2 grids are created when this runs?
because it's running twice, you have 2 objects with this script on it
I thought of that but I cant even see the script
oh I see it ty
Does someone know what the Tilemap class is because "Tilemap" doesnt work
https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap.html
you know you can just use google yourself
i tried and it says tilemap but the name doesnt work
have you imported the package?
have you added the correct namespace?
I thought unity engine included everything
don't just think, know, that is why documentation exists
ok ty
you can filter the hierarchy to show you certain objects with certain scripts
t: Player
if you type that in the hierarchy, it will show only game objects with Player component attached to it
never knew that thank you
public class interactableTileMap : MonoBehaviour
{
Grid grid;
private Vector3Int mousePostion;
Tilemap tilemap;
[SerializeField] Tile tile;
void Start()
{
grid = new GameObject("PlayerGrid").AddComponent<Grid>();
tilemap = new GameObject("Tilemap").AddComponent<Tilemap>();
tilemap.transform.SetParent(grid.transform);
}
// Update is called once per frame
void Update()
{
mousePostion = tilemap.WorldToCell(Input.mousePosition);
if (Input.GetMouseButtonDown(0))
{
tilemap.SetTile(mousePostion, tile);
}
}
}
does someone know why I am unable to set a tile in game with this code?
I have tile set to a Tile asset and I moved the grid to the top of every gameobject so it should render first
Input.mousePosition returns screen space position, not world. Convert it with Camera.main.ScreenToWorldPoint
ok ty
been coding for the past hour, and im getting this error,
Debug.LogError("Can not Instantiate before the client joined/created a room. State: "+PhotonNetwork.NetworkClientState);
from the multiplayer launcher
mousePostion = tilemap.WorldToCell(Camera.main.ScreenToWorldPoint(Input.mousePosition));
I converted it but it still does not place anything
is it better to set values in the start or awake method instead of declaration?
i noticed that the editor does not update values if you change it in the field declaration
awake for self.. start for others
(set up yourself in awake) (grab references to other things in start)
allows their awake to run and set themselves up before grabbing
thanks
set them editor if you can. Usually awake is used like a constructor to develop the behaviours, or perhaps constuct types which you otherwise couldn't serialize with the editor
but setting them in editor won't change the value in the code
is that the intended way
it will..
if u have a script that sets a float to 5.. myFloat = 5f; then it will automatically put a 5 in the inspector...
if u change that to 10.. the code will use a 10 for that variable
the code will still say 5.. but it uses w/e is set in the inspector
so it works both ways, i didn't know that
if u press the three dots in the right corner of the component in the inspector and press Reset
it will put w/e u have in the script back in the inspector
thanks, that's useful
Is it possible to make a new gameobject in code of a given asset?
So if i have a cube asset which is an object, can i create that in code
Doesn't really make sense what you're asking. Are you wanting procedurally create a mesh or instantiate your cube?
Instantiate i think
is it fine to ask questions on what a certain snippet of code does? im following a tutorial for walking on walls and am having trouble figuring out whether a certain snippet rotates the player or the camera
If the snippet is self contained, it should be fine. Else you'll need someone to possibly look over the entire tutorial to figure out what that piece of code does. Doesn't hurt to try.
can i put rich text on this variable? it seems to not register
i have this ramp model i downloaded. i have a player character that is constantly moving forward. i want the player to go up the ramp. the player has a rigid body
what do i need to do and code to make this work?
What's the question?
im trying to figure out if it rotates the player or the camera
it is in a movePlayer script
So foward and right are two directions.
h and v are scaled
The resulting move direction is that of the two added together and normalized.
You'd get the diagonal or rather the sum of the two directions.
Forward slash / to end the rich text tag. It errors because \ has a special meaning in C# strings, it looks at the character right after to see if it's a valid escape sequence
\c is not a valid escape sequence, unlike \n (newline) or \t (tab) for example
Rotating would depend on what they do with this directional vector.
If they're assigning it to the forward direction then it'll look as though it's changing direction, relative to forward (in the above, it would be facing in between forward and right)
can somebody explain to me how refering to components work? ive watched alot of tutorials and read alot of forums but nothing seems to work
If processed continuously, the object would be spinning towards it's right direction.
Create a member variable to reference the component and drag-drop the variable into the inspector slot.
If you've got a reference to the object, use GetComponent to acquire a reference to the component
ok so this doesnt work
and is it completly wrong or what, like im just not understanding
Not public = not visible
It needs to be public or serialized to be visible in the inspector.
ok well
oh bruh
Your ide needs to be configured to receive future help though #854851968446365696
If it were configured, you'd get a red squiggly line under TMP_Text and have the action to automatically add the missing namespace
hi
does the ramp have a mesh collider? and does the player have a collider>
so I have a little question, i am going to install a different version of unity in order to get microgame so I could continue my course, do I have to install all the modules for build support as well or simply install the 1.27GB dev tools? This might no be related to coding because I just started to use Unity and I'm doing a course to get started
well, does the course have certain things you need
if you have no intention to actually build the game for export then you dont need all the build tools
idk, the comment from the course say to install the version 2021.3.33f1 because the current version I first donwloaded does not have microgames. I'm literally doing a "Get started course" so I don't know what other things to get since it's from the comments
btw am I allow to post screenshots for context?
yes, please, the more information the better
Just install what is offered by default, if you are missing something you can always add it later
yep, then you're good to go
k thx
hey guys ive recently encountered a weird error which doesnt let me work on my project. on this message i answered to my old messages (my old problem) and now i have a new problem. my unity doesnt let me install the editor application, i tried the other version aswell but encountered the same problem. is there someone that knows about this problem?
public class Shoot : MonoBehaviour
{
public GameObject bulletPosition;
public GameObject bulletPrefab;
private Camera cam;
[SerializeField] private VisualEffect muzzleFlashEffect;
public float bulletLife = 4f;
private Quaternion defaultRotation;
[Header("Recoil")]
[SerializeField] private float minRecoil;
[SerializeField] private float maxRecoil;
[SerializeField] private float recoilSpeed;
private void Start()
{
cam = Camera.main;
defaultRotation = transform.rotation;
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
ShootBullet();
HandleVisuals();
}
}
public void ShootBullet()
{
GameObject bullet = Instantiate(bulletPrefab, bulletPosition.transform.position, cam.transform.rotation, null);
Destroy(bullet, bulletLife);
}
private void HandleVisuals()
{
StartCoroutine(Recoil());
}
IEnumerator Recoil()
{
float recoilIntensity = Random.Range(minRecoil, maxRecoil);
Quaternion targetRotation = Quaternion.Euler(recoilIntensity, transform.rotation.y, transform.rotation.z);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, recoilSpeed * Time.deltaTime);
yield return new WaitForSeconds(0.5f);
Debug.Log("Reset");
transform.rotation = defaultRotation;
}
}
Can anyone tell me why the recoil is extremely broken? its an fps controller if that affects it
Are you using a text mesh pro input field? Because it doesn't inherit from input field
Then use TMP_Input or whatever it's called
Yes because the type you used in the code is for the old input field component
public class interactableTileMap : MonoBehaviour
{
Grid grid;
Vector3Int mousePostion;
Tilemap tilemap;
[SerializeField] Tile tile;
// Start is called before the first frame update
void Start()
{
grid = new GameObject("PlayerGrid").AddComponent<Grid>();
tilemap = new GameObject("Tilemap").AddComponent<Tilemap>();
tilemap.transform.SetParent(grid.transform);
}
// Update is called once per frame
void Update()
{
mousePostion = tilemap.WorldToCell(Camera.main.ScreenToWorldPoint(Input.mousePosition));
mousePostion.z = 0;
Debug.Log(mousePostion);
tilemap.SetTile(mousePostion, tile);
tilemap.RefreshTile(mousePostion);
}
}
Does some one know why when this code runs the tiles arent added to the tile map? I have tried refreshing the tilemap and setting the mouse position's z to 0 but it still does not work. The code should set the cell to tile when the mouse is over it.
I am wondering how do i make Vector3.Slerp more pronounced i am making some sort of procedural movement and this is how it looks rn
Im using it to move feet transform from current to RaycastHit.point
my colliders wont make contact with each other, how do i fix this? when i increase one there is this invisable like force that creates a tiny gap between them. but im trying to do a tag system to detect ground so i cant spam jump if im not on the ground. currently im using the ground tag to take care of this but, the player and the ground never make contact (i used debug.log to find if it was even true in the first place)
how do i get the text to change tho? the script is on the player object
.text = health.ToString()
You need to convert it to a string beforehand, otherwise you'll get an error (cannot convert int to string)
got it, where would i include that
Think about it for a second
oh im dumb
ok but im getting this error "TMP_Text.SetText(string, bool)' is a method, which is not valid in the given context"
Yes because you do not need the SetText() anymore
Yes that variable contains the text displayed on the screen
i dont really understand what this error means
You tried to access something on a variable that is null (that did not have a value)
how would i fix that in this context? i cant think of any variable that is null
i have the text and the health and im just trying to set the text to the health (i think)
and the bool but i never use that
you dont need to think of which is null, the error already tells you what line it is on
Go through the resource I linked and read
ok but i have on start health is set to 100
at ... PlayerHealth.cs:27
Line 27 of PlayerHealth
alright ill read it
what am i suppossed to be reading that helps here? i literally just have a variable and it is not null and it is giving me an error that says its null. i understand that this page is supposed to help me but ive read all of this and now i know nothing more relating to what i need help wtih
so clearly i am not getting help here
thanks for the attempt
i have a variable and it is not null
The error says otherwise
You think it is not null, but in reality it is null
Should I use git when working on my projects?
An integer cannot be null, ever
You went through each of the troubleshooting sections? Because rn you're arguing about an integer being null, which would indicate that you haven't
So I have a vector3 math problem. I have an object at position A and an object at position B. Object at position A should move 1f towards the Vector3.forward of position B. How can I do this?
DUDE
"the Vector3.forward of position B" what does that mean?
The vector3.forward of object B
Line 27. What's on it
what you told me to put
So, moving object A in the direction of object B's forward vector? Or something else?
healthDisplay is null. That's the only thing being accessed with the dot . operator
a.transform.position += b.transform.forward
but how is it null when it is this? or am i just stupid
Because in the code, the line right above, you're overwriting the variable value
You are not using that variable. In the line above you replace it with something else
im still getting that error even when removing the line above it
๐ 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.
@north kilnOkay nice, but this is continous, how do I move it X float?
It doesn't stop moving
I guess the error is reported on line 26 now. Which means there's at least one other script that doesn't have the text dragged in
Well if you run the code multiple times it's going to happen multiple times
E.g. If you have it in Update it's going to happen every frame
Just a matter of making it run when you want it to run.
oh my god im so dumb. the error just diddnt go away. thats my fault. it works now
thank you and sorry for being rude
Not sure what "move it x float" means
Ah I see, I do have an if check but for some reason it does not go to false, so I must investigate
what does this warning mean?
exactly what it says
Your Card class is a MonoBehaviour
you're trying to create them with new
That's not allowed. As the error says.
what can i do instead? im following a guide from a few years ago, hence the problem
make this class non-mb
The error message contains the solution as well
just read it
There's no way the guide from a few years ago is doing it the way you're doing it
you probably added : MonoBehaviour to the class when the tutorial did not.
4 year old video
lol
this is not the Card class
DO everything the same way as in the video, and it will work
omg just noticed they're using notepad++
oof
Yeah, shit tutorial ๐คฃ
it's very possible someone who is using notepad++ might also have just made this mistake in the tutorial too
๐
lol curiosity is peaked, now i gotta look at the series
ya theres also no narration...........
but somehow its 70+ episodes and even goes into opponent AI
ashmed but I do that too sometimes on my vids, when i'm away from my home setup and no mic :\
How to Make Card Game
How to Make Card Database
โ๏ธ Fanpage: https://www.facebook.com/CezarySharpOfficial/
๐ Shop: https://www.facebook.com/CezarySharpOfficial/shop
๐ Website: https://www.cezarysharp.online
๐ณ Patreon: https://www.patreon.com/cezarysharp
๐ต Support: https://www.youtube.com/channel/UCYFnQ_5dtfkdG210lL3gh0Q/join
๐ท Pinterest: https:/...
they said later that their english isnt good enough, it is what it is
oh my for once I will say the ScriptableObject cards from brackys would be better than this..
wow you actually did follow correctly
the tutorial is just bad
welp lol
I can only hope and assume they make it into a regular class at a later point..
they even put a constructor..
atp should i just look for a different tutorial
this is step 1 and its already bad, I'd say so
alright then
https://youtu.be/aPXvoWVabPY
this should get you somewhat started much better
When making a game you need a good way of storing data. This is where Scriptable Objects come in! In this video weโll learn how to use them by looking at an example: Making cards for Hearthstone.
โ Project on GitHub: https://github.com/Brackeys/Scriptable-Objects
โฅ Support Brackeys on Patreon: http://patreon.com/brackeys/
ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท...
I know, brackys I know.. but this one is okay
tbh ive just been really stuck, need to cook up a card game quick for a competition, at least the bare bones, but most guides i see dont go in-depth into the game logic of the cards, and im too confused on where to go after that
the extensiveness of this tutorial was why i picked it up initially, even though it was scuffed
Card games are quite complex
they'll require a strong understanding of Unity fundamentals
as well as programming fundamentals in general
very exhausting too , I made only 2 and it drains me
especially if you're looking at Hearthstone or MTGA for inspiration
MTGA is a software engineering wonder to be perfectly honest
rip, only planning on making the cards be like "draw 2" or "double attack", more akin to old yugioh
knew more complex stuff was out of my field
but its already lookin hard...
You can probably do something pretty simple without too much grief but it gets very complex very fast
especially if any of the cards modify the effects of any other cards in any way
or if there is ever a chain reaction of events
what kind of game that is 2d should I make as a beginner
You could try to recreate a "classic" game like pong, brick breaker, top-down chess, checkers, connect 4, solitaire, etc or try searching for games that fit something you want to focus on learning such as animation, physics, UI, etc - if youd rather create your own small 2D game, id then maybe start with a GDD and Trello board to plan out exactly what assets youll need, and the scale of the game, though the latter may be a bit complicated if its your first ever project, it can take a lot of trial-and-error
yeah, typically you need a little bit of experience with basic games before you work on basic projects
from what ive heard, a good first few are pong clones, mario clones, and vampire survivors clones
all are easier to program in comparison to big projects
Hi, why don't I have information about the code like the left screenshot?
Can you make your screenshot bigger of your IDE?
Interesting 
Is that what they call IntelliSense I'm not having?
Well, you need to put a ; first, but I don't expect that to fix your summaries.
no those are summaries
btw why are you mixing use of InputActionAsset and your (confusingly named) generated C# class PlayerInput?
Yeah yeah I'm just tinkering with stuff now, but I'd like to know why I don't have information about the code like the previous screenshot
I'm currently learning the new input system, this is not actual functional code or whatnot
well, fix your compile error
then it will work
btw you can just do moveAction = playerControls["Player/Move"]; for example
instead of that long form you have
Oh that's good, didn't know that, thanks
Perhaps its because you miss all the other Solutions in your project? It probably grabs the summary from there is my guess.
You can enable those in your preferences and recompile your project.
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
No, it was just for me for the screenshot, but these are the solutions I was talking about.
Not sure which one to be honest, I guess Build-in or registry
Ok I'll try now
Then regen project files, and reopen your Visual Studio to load the new stuff.
It was Registry packages! Thank you so much
๐
I was always copying the code in google to see what it does.. lol
I have a question, should I start with 3d or 2d first
Start with whichever interests you the most
One isn't a stepping stone to the other, despite the fact the number 2 comes before 3.
Which would be like saying one should learn to drive a motorcycle before a car because it has less wheels.
Whenever the bool Spawn = True, the gameObject isn't spawning. Here's the code: https://pastecode.io/s/ryoude0d
Fix your formatting, you've been told this before.
And show how you're setting the value to true
This is horrific, why would you do this to yourself! Lol
I am on my phone and i may overlook your code
Your use the spawn only in start and it is meaningless to set it to true in ontriggerenter
So I shouldn't use it in start?
How is the formatting bad?
Also, sorry if I don't respond, I'm playing tetr.io
Then don't ask questions until you're actually prepared to give people your attention? ๐ค
Seems like the logical level of respect
Anyway, as above, what IDE are you using? There are hot keys for auto formatting you should use.
Recommended format
void Method()
{
if ()
{
//stuff
}
}
Or at least the less common
void Method() {
if () {
//Stuff
}
}
Your start wont run after ontriggerenter
using transforms and rotation for a tetris game (it looks like?) is more work than needed. Should just stick to a 2D array
Is that a question?
There's a wild amount of repetition; why is all this split up into different almost identical clauses, when each section could just be wrapped in the shared one?
Ok, I moved the bool, but there's a new problem. I only want the gameObject to spawn once.
how would I make something not visible? like text for example
Ok, I moved the bool, but there's a new problem. I only want the gameObject to spawn once.
so where you want it to spawn in your code, just put the code there
It spawns more than once when I put it in OnTriggerEnter
use a bool to check if the object is spawned
I want an enemy to move towards the player unless it is a certain range and if it is in a slightly larger range it will shoot, it acts super strange moving even when it looks like it should not. https://gdl.space/logisadovi.cs
@tender breach If you're going to ignore the question, you simply won't be posting here.
Nobody knows what "super strange moving" actually means. You might want to share a video.
i just need to rb.velocity to 0
how do I do that?
rn I'm doing transform.forward * 0 but that's ugly
Stop deleting my messages.
Not my question, which I asked twice. You can scroll up to find it because I'm not posting it a third time.
What question am I ignoring?
what ide you use
Vistual Studio
Why is my sprite behind the backround?
It's got a higher Order in layer
Visual Studio
Stop complaining about the formatting, I tried my best
Not a coding question, show your other object
You don't have to try your best, your IDE will do it for you. Format it properly so people can actually read it. This has been an issue with your questions multiple times.
Fix your formatting?
With the bool
Mesh component != sprite component
Sprite ordering isn't the same as a mesh. Move it physically in front of the mesh.
it doesn't even have a layer option so idk what you're comparing both of them to
Oh
Gotcha, thanks
my camera just isnt rotating. even when i attach the script to the camera and remove the Cam. from the transform
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
hey is there an easy way to get the direction from point A to point B? (3d)
ty :3
oh thats fun
Three things:
- Configure your !ide
- Rotation is a Quaternion: https://unity.huh.how/quaternions/members
- https://unity.huh.how/compiler-errors/cs1612
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
but there should be a way to modify the individual values of a quaternion right?
There is, you just don't, because it's a complex number. Use the eulerAngles.
You haven't paid attention to anything I've said
Configure your IDE before doing anything else
Don't access the quaternion.
And use the correct method to modify members of a struct returned by property
Rotation returns a quaternion. A quaternion is 4 values. It is not what you see in the inspector. You do not want to mess with it at all. As Vertx said
Also keep in mind that a configured IDE is required for getting help here
public float GetModifiedSpeedFromCurve()
{
return currentSpeedCurve.Evaluate(stateTimeNormalized)
* AbilitySO.SpeedData.BaseSpeed;
}
Say I want to loop my curve a specific amount of times over this normalized time instead of once throughout the duration, something like stateTimeNormalized / loops or modulo
sounds like integration
is this that really complicated of a problem. I expected a single operator lol
brain sleep
So I opened a project after a long hiatus from Unity. Am I tripping or is there a reason why I can't drag objects around the hierarchy? I can click them and see their properties in the inspector but I can't click and drag them around
maybe got it locked on the UI somewhere
Yeah I was thinking that too but besides the lock at the top which just locks the window to that section I dunno where else it could be
Just try restarting the editor
Can you try holding your mouse button for a few seconds before moving it?
Is this a code related question?
Happy new year everyone
is it possible to disregard warnings that popup?
this is giving me a warning however, I account for it in a different way that does the same thing. its just not recognizing that other way and therefore still shows
Red underline is an error
Warnings can be ignored, errors cannot
You need to read the error message
I think it's just the color scheme. Seems like a warning/yellow to me.
What IDE
vscode
and i account for this with the line at the bottom
You should always await async Task calls because you will eat exceptions otherwise
if the SyncXXX returns you an error then this coroutine never end
is this not effectively accounting for it?
Why use a Task if you're not intending to await it? Use async void
I can try that
So the void removes the warning but it shouldnt cause any issues?
async void is fire and forgive
okay good to know
id never used a task before but i was trying to follow the documentation
i guess i was just a little unclear on that bit
thanks for all of your guys help
hi. im trying to make a ui pop up when you hover over an item/object in-game .i kind of got it to work but it only pops up when i hover over the leaves of the tree and not the trunk part. is this a skript problem or asset problem.
!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.
Selection Manager - https://gdl.space/arewuqabak.cs
Interactable Object - https://gdl.space/poxolocola.cpp
I tried this, still nothing, I stepped away for a bit but now I'll try again
It might just be the project, I imported an asset which might've broke it
Nvm looks like it's all projects, I'll just try again tomorrow maybe a pc restart is needed
Don't crosspost.
From the screenshot it looks to be working on the trunk too, so I'm not sure I understand the issue.
wait
i must have not noticed it
ok
i think it was a glitch
heres the real image
Who let me cook
You want to add some logs in your raycast logic to see what's going on.
oh ok
I'm sort of following along this hex grid tutorial https://catlikecoding.com/unity/tutorials/hex-map/ and I'm currently looking at the way they handle color & terrain textures... The way they handle it in the terrain tutorial is by using a texture2darray and then passing a value to the shader to have it know which terrain to use for a specific hex tile.
What are the advantages to this approach as opposed to having one texture material and then using UVs to map the hexes to a specific terrain? Just trying to understand the thinking behind this approach
Hey im watching a unity tutorial but I don't seem to understand what does the f after number means
float
if you dont type the f and decimal by default is double then you will get compile error
Oh so I should type f only if it has a decimal point?
Generally, yes. Except if it's unclear and could provide different results with integers, like division
Though it's harmless to specify
yes, since double cant implicitly convert to float
in c# any number in higher precision cant implicitly cast to number with lower precision
ah i got it thanks for the help!
The approach with multiple textures will make it possible to change the texture of particular tile types without modifying the texture itself. Configuring an array of textures will be more intuitive than configuring UVs. It also makes it easier to avoid mistakes.
Not really. You type f if you want it to be decimal. There are some methods like Random.Range that work differently depending on the argument types, e.g. Random.Range (0, 2) will return a random integer in range [0, 2>, so it's always 0 or 1. On the other hand Random.Range (0, 2f) returns a float (because 1 argument is float), which can return any number in range [0, 2], so it can be a value like 0.001f or 1.356f. Also when it comes to math, the result is usually integer if all numbers also are integers, but the result will be different type if numbers are of different type, so 7/2 will return 3, but 7/2f will return 3.5f
Alright, fair enough, ty
It's a type of data that can contain decimals or fractions.
Float is 32 bit. And there is double, which is float but can be used for way bigger numbers. Then decimal which is even bigger than double.
If you were to type just whole numbers, it will be int, then the compiler will secretly cast it to whatever type of number is reasonable. (int to float/double/decimal)
But once you start putting . and make it a fraction, it defaults to double and compiler won't automatically cast that to float for you since. Presumably because float is smaller in bit size than doubles.
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
DontDestroyOnLoad() and Start() have some weird interactions,
im trying to have a refrence to an object with the DontDestroyOnLoad method using the Start method, its not happening
show some code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ClassManagerScript : MonoBehaviour
{
public ClassScriptable ClassData;
private Transform SummoningPoint;
private bool ClassSummoned = false;
public void Start()
{
DontDestroyOnLoad(this.gameObject);
}
public void SummonClass()
{
SummoningPoint = GameObject.FindGameObjectWithTag("SummoningPoint").GetComponent<Transform>();
Instantiate(ClassData.ClassPrefab, SummoningPoint.position, SummoningPoint.rotation);
ClassSummoned = true;
}
}
this guy has a dont destroy on load
that should be in Awake
hold up i think i found the probelm ๐ฟ
ah
this might be it
forgot to add the tag ๐คฆโโ๏ธ
I am implementing a market of goods per town, so 5 towns, 5 markets. What is a good pattern to access these market and check prices for multiple systems. I feel like using 5 instances of marketmanager does not seem good?
DontDestroyOnLoad should always applied on the awake?
yes
Always, no. But in this case where it was used in Start then, yes
right
how would i animate the camera of the player with the animation does playing the animation for the animator in the camera do the job? cause it kinda doesnt do it for me
Why does my square twitch like that when I move to the right?
I made a player movement script and everything was fine, but once I parented the camera to the player, my player started twitching when moving to the right. This doesn't happen if the camera isn't parented to the player.
๐ 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.
Probably due to your condition in Flip:
if (IsFacingRight && Horizontal < 0f || IsFacingRight|| Horizontal > 0f)
That would be true whenever you're moving right
guys, i made an interactable object wich if the player is in the box collider area the text will appear. But in this problem it become opposite, because when im not in the box collider area the text will appear but if i get in the box collider area the text not appear. Can someone help me?
You'll need to share the relevant code
this is my interactable 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.
Ok I have a frustrating code issue. I want to make it so when a button is pressed, collisions between two objects are ignored. The code I have is this:
if (collision.gameObject.CompareTag("Bookcase") && phaseWalls == true)
{
Physics.IgnoreLayerCollision(6, 3, true);
}
phase walls is a publically declared bool set to false. Using the code in update method
if (Input.GetKeyDown(KeyCode.Space))
{
phaseWalls = true;
StartCoroutine(PhaseWallTimer());
}
}
IEnumerator PhaseWallTimer()
{
yield return new WaitForSeconds(7);
phaseWalls = false;
}
This works, I can't move through the object at start until spacebar is pressed, then I can, and 7 seconds later the bool is set back to false (I can see this is the case because the public access modifier lets me see when the box gets ticked on and off). The problem is, that if statement in the collision enter method never re evaluates, so it never turns off again. Any ideas? I can post whole code if need be but didn't want to have too much written here.
Share the code properly. Also, the other script that actually enables/disables the text.
Share the code properly
!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 can i edit this properly?
https://paste.ofcode.org/pRhgpEpKAfYY6kdfAH8guT
So yeah again,
Ok I have a frustrating code issue. I want to make it so when a button is pressed, collisions between two objects are ignored. This works, I can't move through the object at start until spacebar is pressed, then I can, and 7 seconds later the bool is set back to false (I can see this is the case because the public access modifier lets me see when the box gets ticked on and off). The problem is, that if statement in the collision enter method never re evaluates, so it never turns off again. Any ideas? I can post whole code if need be but didn't want to have too much written here.
The last else if was just a last ditch effort to force it to evaluate going back to false, that didn't work obviously
you have to edit the UV of the mesh
edit it on blender
alright thanks
It doesn't seem like the first script is doing anything at all. Aside from providing the text.
Your second script uses a raycast to determine if the player is pointing at the object to display the text.
Can someone explain and show me an example of how to synchronize variables via rpc for a health script. Using netcode for gameobject

i see, thanks for the answer
The solution is simple: move the Physics.IgnoreLayerCollision(6, 3, false); line to the coroutine.๐คทโโ๏ธ
yes that worked thank you, but I'm still confused as to why the way I had it wouldn't have worked
that bool would be set to false, and shouldn't that if s
statement re evaluate when I collide with the object again?
Because when you ignore collisions, the OnCollision method is not called
So that if statement is never evaluated.
ohhh yeah duh. thanks for the explanation
Hey all, I'm currently working on the fundamentals to a simplistic chess game and i've ruin into a possible future roadblock that may require me to redesign how i've written my code.
I have an 8x8 chess board defined by a 2d array of Square objects "squares"
public static Square[,] squares;```
This is then populated with standard `Square` objects. All `Square` objects have the variables:
occupyingPiece, which is a `Piece` Object (Shown Below)
position, the position on the chess board and in the array, self explanatory
instantiatedObject, a `GameObject` that is the instantiated object whenever a square has a piece on it
When i want to alter a piece's position or destroy it i edit the values of the `Square` in that part of the array.
If i want to move it, the initial square will have it's occupyingPiece and instantiatedObject set to null, while the new position's `Square` in the array gets the previous occupyingPiece and instantiatedObject, then the object's transform is also changed for it to visually move
Below is a snippet from Pieces.cs, which outlines each of the individual pieces' behaviour and caluclating the valid squares that they're able to move to the Pawn is just one example of an implementation, this would be done for every piece in the game
```cs
[CreateAssetMenu(fileName = "Piece", menuName = "Chess/Piece")]
public abstract class Piece : ScriptableObject
{
public Colour colour;
public GameObject prefab;
public abstract Vector2Int[] GetValidSquares(Board.Square[,] boardState);
}
[CreateAssetMenu(fileName = "Pawn", menuName = "Chess/Pawn")]
// Individual Piece Definitions
public class Pawn : Piece
{
public const short VALUE = 1;
public override Vector2Int[] GetValidSquares(Board.Square[,] boardState)
{
return null; // Placeholder for now
}
}```
In doing this i've realised there might be an issue in my logic, If i want to move a piece by clicking on it in the actual game space, that piece is just an object with no actual logic behind it, as the Square holds all the information for that GameObject, so I get the feeling that the way i've done it isn't great. Does anyone have any recommendations of how else i should do this so that I can easily use the logic for the piece when the player is actually looking at the gameObject in the game space? Hope that makes sense and thanks for reading. If you need anymore context lmk.
There are innumerable ways to go about it, but if you want to avoid altering the code too much, you could make the square to subscribe to an event of a Piece that triggers when the players clicks on it.@inland cobalt
I'm not that far in so I don't mind redoing bits if necessary if it helps me out in the long run
hm, this line of code doesn't appear to work, judging from the fact that the length of the array is zero- there is no error message, would you have any idea as to why it doesn't function?
Then let some kind of board manager know what piece/square is selected. And when you click another square, move the piece from the selected square.
I don't think your approach is bad necessarily. As long as it works, it's fine imho.
ah that makes sense, so you mean i can work out the actual transform position of that piece/empty square im hovering over at then compare that to the array, as i can use it's relative position to the board?
No, you don't need to look for/compare anything if you pass the data like this: piece -> tile -> board manager.
And to pass it you can use events.
Alright, thanks
Probably nothing overlaps that circle๐คทโโ๏ธ
i made it have a radius of five, and the randomTargetLocation is certainly within 5 units of something (i.e the enemy gameobject)
Share the updated code then.
Also, does the enemy have a collider?
both a rigidbody and 2D collider
What do you think the third parameter of the method does?
oh
I assume that I misunderstood the function of the third parameter.
I thought it made the method only check for gameobjects in that layer
Yeah. It is not the layer index. It is a layermask. 0 would make it check none of the layers. Basically always returning no overlaps.
that explains much, thanks
What would be a good way for switching weapons? I don't really see this as a good option. https://i.imgur.com/m5Clz7n.png
Something like:
inputToActionMap[input].Execute()
Hey all, back again with a problem i've ran into.
Here's an example chess board in my scene. What i want to do is to figure out what square my mouse is hovering over, by getting its coordinates. Now my initial idea was to draw a ray from the mouse aiming straight down so that it would hit the board in the appropriate square, but i'm struggling to figure out how to go about doing this, if anyone could offer me any suggestions that would be greatly appreciated.
Also to note the chess board may not be a birds eye view like shown in the picture, the camera could be looking at an angle as if you were at a real chess board for example
Look into the strategy pattern. Have each weapon as a class (with a weapon base abstract class or interface) and then each the player could have an "Equip" method
Maybe transform the hover position into the board local space and the get the tile coordinates with some math.
Sorry i'm not quite sure i understand, mind elaborating on this?
Which part?
transform the hover position into the board local space
Use Transform.InverseTransformPoint for that
https://docs.unity3d.com/ScriptReference/Transform.InverseTransformPoint.html
basically, it returns the position relative to the object.
Then, depending on where the pivot point of the board is and the tile sizes, you would calculate the tile coordinates.
And to get the mouse's position would i just do Input.mousePosition right?
Yes. But you wouldn't transform the mouse position.
You need to cast a ray at the mouse and get the hit position. You need the position on the board in 3d space. Not a 2d mouse position in screen space.
and i'd cast this ray from the camera correct?
yes
How would i cast it in the direction of the mouse if the mouse position is 2 dimensional though? Thats the bit im unsure on i think
What's line 37?
Alright, so i'm casting a ray like this towards the mouse
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);```
You said i need to cast a ray at the mouse and get the hit position, but i'm not getting any raycast hits out from the Physics.Raycast function
```cs
if(Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity))
{
Debug.Log(hit);
}
What code? What about answering my question?
Nothing prints in the console?
Does your board have a collider?
Ok, well multiplying by a method is not gonna work(or do anything even if it did).
Oh i'm a muppet i forgot about the collider lmao, sorry for wasting your time, thanks for the help
You mean the rb rotation line?
Does it work if you comment out the code in Update?
Is your camera on the same object as the script?
I don't see how it would've worked.
Move the camera to a child object.
Yes.
before what?
What object is the script on?
Take a screenshot of it's inspector.
There seem to be more components
Probably lack of interpolation on the rb or your movement/rotation breaking it.
@teal viper Sorry to bother you again, I've written this fucntion now that mostly works, but as you get to the edge of the field of view, the values seem to get increasingly innacurate, which im unsure how to solve, i think its because of the way the rays are being done and that the ray should stop at the mouse position and go down instead of continuing onwards, any idea?
Here's my code
Vector2Int? GetSquareAtMouse()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit))
{
return new((int)hit.point.x, (int)hit.point.z);
}
return null;
}```
You don't transform the position into the board local space
Ah, of course, I completely forgot about that, thanks again
Vector2Int? GetSquareAtMouse()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit))
{
Vector3 localPoint = boardPrefab.transform.InverseTransformPoint(hit.point);
return new((int)localPoint.x, (int)localPoint.z);
}
return null;
}```
I've done this but it still seems to be off like before, have i done it incorrectly?
Seems to be fine, assuming your tiles are exactly one by one units wide.
How exactly is this inaccuracy expressed? How do you confirm it?
Implement it.
You should probably look up an fps controller tutorial at this point.
They are one unit wide yes, I'm just logging the return value of that function every update, and moving my mouse over squares.
Wait a minute, it looks like it may be rounding it
doesnt (int) conversion just eliminate the decimal right?
It does
Ah i know what my fault was, i wasn't accounting for the border being 0.5 units wide, so my measurements were 0.5 off, and the removal of the decimal made it confusing, i was thinking the ray kept going which is why it threw me off
for what is a list more useful than an array?
for when you don't know how large it will need to be up front
ok thanks
Iโm a complete beginner coder whoโs following a tutorial online but something has gone wrong and I donโt know what to do from here. Iโm trying to program a 2D pixel sprite to walk and Iโve followed the tutorial exactly but the script (using C# if that makes a difference) is refusing to attach itself to the Prefab. Iโm saving it onto the prefab and trying to attach it in multiple different ways but it wonโt work, does that mean Iโve gone wrong in the code somewhere?
sounds like you have script errors, screenshot your ide and console
the script (using C# if that makes a difference) is refusing to attach itself to the Prefab
Scripts don't usually attach themselves to things. Normally you would be doing it manually
Sorry for the poor photos, I donโt have discord on my computer but this is the script
You need to show:
- What happens when you try to attach the script
- The console window in Unity
Iโve added a playercontroller script and Iโm editing it but no matter what it doesnโt seem to appear on the prefab
Do this
there are obvious errors there
Ah okay sorry, first time coding ever so Iโm not really too sure, Iโll try going back through the video
Yeah ok looking at your screenshots this part:
Iโve followed the tutorial exactly
Is incorrect
because yes you have obvious errors in the code
and your biggest issue is your IDE is NOT configured
so it's not even showing your errors
the first order of business is to configure your IDE
!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
Ah okay Iโll do that thank you so much
Hi, is it recommended to use the new input system at all? I'm only a beginner and trying to understand it, I configured 3D movement with the help of a tutorial, but I can't get the blend tree movement animations to work at all.
imo you should learn old input system first and then learn new input system
For a beginner it will be difficult to use as it has a bit higher learning curve and requires intermediate knowledge of C#
what I learnt so far about the old input system is just how to check if keys are pressed etc.
just wanted to let you know that just changing to struct worked perfectly thank you!
Yes that's what input systems do ๐
Ive been using unity for a few years and goddamn that new input system is a mess to work with
I wanted to make a keybinding system which is really hard to do with the old one
but nah I cant even be bothered with the new one
I see, and what I understood from the new input system is that its advantage is to have keybinding for keyboards, gamepads, etc... at the same time
no not at all
you can do that in the old system
#๐ฑ๏ธโinput-system exists btw
way harder to do but there is some resources in the asset store that let you easily
u just got to hand that cash out
understood, yeah I'll try talking there
not at all
in the default Input Manager you can add multiple bindings for the same axis/button without issue
yah I was talking about rebinding ingame
not in the inspector
nobody mentioned rebinding in game
bad choice of words but thats where I was trying to get
But yes, runtime rebinding is one advantage of the new input system
I dislike the new one because for me it overcomplicates what is simple with the old one
what is runtime rebinding?
If you want to stay simple, you can do so in the new system too. It just provides more flexibility.
when u are in a game and want to change the key for the same action
Rebinding keys at runtime
i.e. allowing the player to rebind keys
do you face any disadvantages or you're fine with it? I'm aiming for a first person co op game
I'll give it a go since last time was like last year and I didnt have a lot of knowledge
it's not possible with the old input system to rebind your keys?
what about people with different keyboard layouts
It's not possible to do so at runtime without creating an additional abstraction layer, no.
I see then, it's clearer now
well for begginners go for the old one first since its really easy to use. but man fps coop game for a begginer?
goodluck with that
no, I'm not making it right now, but that's a project for the future when I'm comfortable after a year or more
if u want to get stuff done and learning fast do game jams, they are the most fun
and for now stick with the old one
what's that?
go to itch.io and find game jams. its where you make a game in a time frame (depends on the game jam) and gets ranked at the end everyone that submitted a game can rate the games
better than force myself learning the new input system you'd say?
normally there is a theme too
that sounds fun!
if you want to start learning to make games yes
if you dont have experience in the making of a game
with a simple input system
imagine trying to make and figuring a harder one out
yeah I don't have much experience
great, thanks!
no worries
and if you are trying to learn start with games with only the default unity shapes
my first 2 were like that
and both made in 2 days for game jams
sure! I'll do that : )
thanks
one more thing, I remember having pop ups from unity to use the new input system, which is why I started learning it lol. so to fix that, is using "Both" input systems okay or is there a way to force the old input system without unity pop-ups?
I use both and I've never had any problems
Sometimes just doing Input.foo() is simpler than the boilerplate that comes with the new input system
okay so you can have it set to "both" and act as if you're only using the old input system yeah?
Well....if ur just gonna use the old system just use the old system and don't install the new one
exactly
ah yeah so I'll uninstall the new input
dont waste space in your projects with stuff u wont be using
Yeah for a beginner anyway just use the old one
The new one isnt a requirement
And it's really complex
Yeah ofc
does anyone have idea how to make spotlights toggle on/off according to weather/time of day/fog in the scene ? I tried darkness, tried height of sun, tried density of fog, none is working . I want that my spotlights toggle if the visibility is bad on the scene
if its a consistant time try to InvokeRepeating
hello everyone, I'm new here ๐
I found a game project files on GitHub and want to access the project in unity but upon compiling I am facing couple of compiling errors.
If you want to see the project link:
https://github.com/kennedyvnak/unity-metroidvania
hey guys, I'm trying to create a mesh from a parametric function but i can't wrap my mind around creating triangles from the vertices. Should i post my code here I don't want to post a big block of text hahah
Did you modify the code at all?
no
The code from github looks like it shouldn't have those errors
try redownloading the file(s)
My friend also got the same error.
I mean that class clearly implements those things ๐ค
https://github.com/kennedyvnak/unity-metroidvania/blob/6a8f7668fe589b81f891b71ede5be480a938e281/Assets/Scripts/Systems/Input/InputReader.cs#L104
but i guess it's possible it has a bug
github said to use a specific version, and I installed exactly the same version
https://gdl.space/vuhedasupi.cs
Okay i just found about pasting code, this is my class and i'm trying to create the triangles from the points I construct
When i try to do it like a grid parts of sphere doesn't get rendered
doing
http://www.songho.ca/opengl/gl_sphere.html
I've used these in the past that work pretty well
This is exactly what I was looking for, thanks!
also if you havent, get more simpler primitives rendering before the sphere (quad, cube)
Yes definitely, I think I rushed a bit too much lol
I'm trying to create a parametric surface plotter for my differential geometry class
But I really should try to render simpler stuff first
!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.
Guys how do i make an interface type object show up on Inspector with [SerializeField]?
Im doing a script to attach to any Interactable/Hittable objects to show up or hide gameobjects based on an event
target script:https://hatebin.com/fbcbnfwfqqusing
game manager script: https://hatebin.com/upeosspvgq
basically what those two do is making a game where objects are thrown in the air and you gotta click on them to destroy them, the game faces a gameover screen if they touch a sensor at the bottom of the screen or if you click a "bad" object, so far i couldn't find what i missed because as soon as i start the game, the objects are not instantiated, so that means that the boolean value "isGameActive" is false, but i cannot find why
Cant serialize interfaces outside of serialize references
look at the code
void Start()
{
StartCoroutine(SpawnTarget());
scoreText.text = "Score: " + score;
isGameActive = true;
}
IEnumerator SpawnTarget()
{
while (isGameActive)
You start the coroutine, isGameActive is false, so the while condition is false, so the coroutine ends. Then you set isGameActive to true
So how do i do instead of using interfaces? Because an item can have multiple interfaces like Interactable or Hittable.
You serialize by the type*, not the interface in this case
in void start() isGameActive is true
but i wanna make that also a gameobject that is not an item can be Interactable but not an item (like zombies).
but not until the coroutine has already started