#💻┃code-beginner
1 messages · Page 86 of 1
Are you iterating a list or transform?
transform
foreach (Transform obj in parentTransform)
{
Destroy(obj.gameObject);
}```
By the way is there any way to destroy them but with a timer instead not at the same time?
This should destroy them 1 second apart
int delay = 0;
foreach (Transform obj in parentTransform)
{
Destroy(obj.gameObject, delay);
delay++;
}```
I put the objects which have animations on them in a empty parent and now the animations aren't working??
thats not how you use animations
so they gotta be seperated?
you need animator
oh on the parent?
put the animations in the Animator controller on parent
hello people, I have another small issue, I'm trying to delete a "grid" from the hierarcy but for some reason I cannot? right click delete or pressing delete from the keyboard does not work, any ideas why that may be the case?
what you trying to do?
this
restarting the project fixed it.
hey guys. can 1 game object have more than 1 tag?
no
oh. okay
I wanna make my button change color from red to green when clicked and reverse. i tried this but it didnt work
maybe instead of Color.--- i should put the hex code?
Frist step is make sure your code is even running
pretty sure it is
oy, i have a maincamera that is in a secondary scene added additively. But now i want a canvas that has screen space camera in the main scene, but then i can't reference the maincamera across scenes. Are there any workarounds? I despise screen overlay, specially because i animate stuff and then i don't have a reference to the main scene because it is so huge compared to the actual scene
How do you know? You need to make sure
Use debug.log
cant u switch the cam on the component via code?
Camera.main exists
i made sure, it is running
How did you check
Ok and where did you put it?
Ah camera.main works across all scenes?
on the top
What about inside the if statements?
thats a good idea
!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.
the if statements arent being activated

Hey guys, I have this GameManager script where I save the player progression when he dies and reload the scene. What happens is that if I die and reload the scene its fine, works good. But if I am killing the final boss of the mini game, and I die and the scene is reloaded, all the enemies desappear but not the boss, what could be? https://paste.ofcode.org/x5Tkj3nx55nAee5mvDBgnD
where do you assign this color the first time ?
I recommend you use a bool called 'Selected' and change the color based on that value.
this is the script
so you never set to one of those colors for the first time ?
its probably neither when you run that function
no i thought it would just set it to the color in the editor
how ? it doesnt change by itself lol
try putting buttonImage.color = Color.red
in start for example
and see if function works after

!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.
tree generation doesnt work https://gdl.space/lofawemige.cpp
@wintry quarry @rich adder lol this worked, my bad thought i had tried something similiar in the past, ty a bunch
Hi I finished a wave script and found out about animation rebinding can someone explain what it is to a beginner?
Right now cloned objects spawn but I want them to move like I assigned their original to move
not sure what I did but you're welcome 
void Start()
{
myCanvas.worldCamera = Camera.main;
} xDDDD
how do i use constraints in unity 2d to freeze a moving bullet on collision with an object
Oh the camera thing! perfect! glad you got it working 🙂
This script almost has nothing in it related to what you described. Also those if statements are the same.
What debugging steps have you taken
in code ? rb.contraints ?
Well basically, there I just reload the scene. Not sure how it works but all the enemies desappear and its fine. But if the boss is there he is the only one not to desappear. Not debugging steps yet as I am not sure how to debug it to understand why the boss is the only one staying there even after the scene is reloaded. And that happen of course only if I am killing the boss and die.
this^ also pretty sure once you type = VS will show you all the proper enum options
How can I change the player's Y rotation to be the same as the cam's Y rotation? I tried setting the rotation directly but it doesn't work
I used Cinemachine to make a FP cam
use the euler angles
what do you mean? cause I tried transform.rotation.eulerangels = cam.transform.rotation.eulerangles but it didn't work
If this is really the only relevant code, then I'd assume your boss is in a scene by itself. Theres really not much anyone can suggest because theres so little shown like how enemies even are spawned in the first place
sweet, but RigidbodyConstraints2D.FreezeRotationX doesnt seem to exist for unity 2d
2D doesn't rotate on X
Because a Rigidbody2D can't rotate on the X axis
Hmm, well boss and enemies are spawned using instantiate method. And they are inside the same script that is the SpawnManager. I though reloadsecene would start all from scratch no matter what I have in the scene.
on what axis does a rigidbody2d rotate on
you only need the Y axis right ?
yes
The scene will reload properly, you should debug stuff in your spawn manager then and see what differences there are when you get the bug vs when you dont
Look at the inspector for the rigidbody, see what rotation axes it has available in the constraints
Ok, thank you!
think you can do something like
var myRot = player.rotation.localEulerAngles;
myRot.y = cam.rotation.localEulerAngles.y
player.rotatation = quaterion.euler(myrot)```
hi guys, wanna make a game but still not too experienced. wanna make a game that basically looks like command prompt, and it asks you questions like age, name, etc. and predicts your future, wanna make it an analogue horror game and when the game says "when your going to die:" it says tomorrow, flashes a name and closes. tried to find a tutorial but cant really find anything
if your whole game is in a command prompt, then unity is not the right engine for you
ah okay, what can i use?
you don’t need a gameengine for that tbh
looks like, wanna flash a name throughout the entire screen
wanna add vhs and background stuff to make it even more scary
idk, but i still don’t think Unity is the right tool for this
you should try something like python
honestly true, mb
yeah. pygames is probably a good start
pygames really good for multiple windows and stuff like that
💩
alright ty
pygames is aight but you can also just make it in c# without unity
assuming you want to use unity later lol
autofiller ?
what the hell is that lol
umm like gives you options when ur almost done with writing the word
idk how explain it
not really necessary ig just see some people have it
!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
thats just intellicode
or copilot
depending which one they have
@safe carbon I believes its in the Visual Studio Installer, Click Modify, then install the "Game development with Unity"
Thank you good sirs
dont crosspost
also this alone isn't helpful to anyone willing to help, you haven't even posted the code with it
The code is not necessary, as it's a tilemap collider bug
then why are you in a code channel
posting in multiple code ones none other
if you think its a tilemap bug then #🖼️┃2d-tools or #⚛️┃physics.
#💻┃unity-talk as last resort
void generateTree(float x, float y)
{
//Define tree
//Generate Log
int treehieght = Random.Range(minTreeHieght, maxTreeHieght);
for (int i = 0; i <= treehieght; i++)
{
placeTile(LogTrunk, x, y);
placeTile(Log, x, y + i);
}
//Generates Leaves
placeTile(Leaf, x, y + treehieght);
placeTile(Leaf, x, y + treehieght + 1);
placeTile(Leaf, x, y + treehieght + 2);
}
It places like 7 logtrunks
its hieght of tree
i see a leaf lookin like a triangle or sum
want full code
well no guarantee I can be of help but at very least post the whole script maybe someone knows
!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.
so whats wrong again ? placeTile is not running the loop ?
well yeah you never increase by i
which way is supposed to spread?
your x y stay the same why would it not spawn in same spot lol
so you only need 1 put it outside the loop
placeTile(LogTrunk, x, y);
for (int i = 0; i <= treehieght; i++)
{
placeTile(Log, x, y + i);
}
//Generates Leaves
placeTile(Leaf, x, y + treehieght);
placeTile(Leaf, x, y + treehieght + 1);
placeTile(Leaf, x, y + treehieght + 2);
TY XD
or actually make it only place it if its first iteration
this way your placetile log doesn't run first iteration
you dont want a log inside a trunk log
ty
for (int i = 0; i <= treehieght; i++)
{
if(i == 0){
placeTile(LogTrunk, x, y);}
else {
placeTile(Log, x, y + i);}
}
//Generates Leaves
placeTile(Leaf, x, y + treehieght);
placeTile(Leaf, x, y + treehieght + 1);
placeTile(Leaf, x, y + treehieght + 2);```
hi, how can i use the polygon collider to see if its collide with another object?
i can't find an example on google
so i need to add rigidbody on it
either this one or the one you are colliding with
also depending if you want Collision or just a Trigger
ty
https://unity.huh.how/programming/physics-messages/3-trigger-matrix-2d
this will tell you which rigidbody interacts with what
2 static rigidbody so i think it will be ok
incorrect. notice how static trigger and static do not produce a trigger message
nor does static trigger and static trigger
2 motionless bodies, where is the physics..
so i need a non rigidbody and a rigidbody
like I said before , no you only need 1 rigidbody between two colliders
i would also like to point out that trigger/collision messages will not tell you if the object entirely overlaps the other object as was your goal the other day
yes, but that is a lil bit hard.. because i have the same object
both objects use the same prefab
i scripted that..
what are you doing exactly ? whats the end goal here ?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
i want a trigger when the planes
overlaps
why
how do i get an animation to change states on collision via the animation controller
its a rule that the plane can't overlap
your overlap points can get you that info
if they don't hit anything or if they hit another plane object then they cannot be placed, it's that simple
usually parameters
https://docs.unity3d.com/Manual/AnimationParameters.html
how do i define a parameter for the animation controller
why i dont see the spotlights / lights in game but in editor yes
this is a code channel
how could i make sorting order of leaves 1
void generateTree(float x, float y)
{
//Define tree
//Generate Log
placeTile(LogTrunk, x, y);
int treehieght = Random.Range(minTreeHieght, maxTreeHieght);
for (int i = 0; i <= treehieght; i++)
{
placeTile(LogTrunk, x, y);
placeTile(Log, x, y + i);
}
//Generates Leaves
placeTile(Leaf, x, y + treehieght);
placeTile(Leaf, x, y + treehieght);
placeTile(Leaf, x, y + treehieght + 1);
placeTile(Leaf, x, y + treehieght + 2);
placeTile(Leaf, x, y + treehieght + 3);
placeTile(Leaf, x - 1, y + treehieght);
placeTile(Leaf, x - 1, y + treehieght + 1);
placeTile(Leaf, x - 1, y + treehieght + 2);
placeTile(Leaf, x - 2, y + treehieght);
placeTile(Leaf, x - 2, y + treehieght + 1);
placeTile(Leaf, x + 2, y + treehieght);
placeTile(Leaf, x + 2, y + treehieght + 1);
placeTile(Leaf, x + 1, y + treehieght);
placeTile(Leaf, x + 1, y + treehieght + 1);
placeTile(Leaf, x + 1, y + treehieght + 2);
}
!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.
if your goal is to change the sorting order of your tiles, that is done on the TilemapRenderer not individually per tile
if you want them to have a different sorting order than the other tiles, then put them on a separate tilemap and change the sorting order for that tilemap
How do I stop an object from animating if it's not shown on the scene
Everytime I click this UI button I set the object animates
But I want it to animate only when it pop ups
disable the gameobject it's on until you need it
or do you mean it's not reset when you renable it
may need to play() again when you activate it
or put empty state as default starting state
Animator's Culling options in the Inspector. I think it stops animating when the object is not visible by default
Not sure if it works with UI
Wouldn't I need to also program this step
no
I'll check this out
Just troubleshooting something and just wanted to double check.....
Am I using this correct to assign the parent of an object to another object variable?
GameObject doorToRemove = doorChecker.transform.parent.gameObject;
create a new state , right click it and Set as Default
you just need a way to play your animations though (either transition or call Play)
Nevermind doesn't work on UI
Ok
How do I call play as transition doesn't seem to be working?
whats not working ? u have to show what you did I have no idea
Hey, I'm trying to scale a UI image by a factor of two but so far setting the size of the gameobject with image.rectTransform.sizeDelta = new Vector2(128f, 128f); hasn't worked and I'm not sure what else would, is there some common way of doing this?
I set a transition and the object isn't spawning at all
or triggering
you set a transition?
show it
prob not a code question though so we can move to #💻┃unity-talk
ty
yo quick question
if(mouseP.x > 720 && mouseP.x < 780) {
transform.eulerAngles.z = -48.068f;
}
i am trying to set the orientation of a sprite
dont want to add rotation to it cause when i use transform.rotate it keeps adding up
i want to set a orientation
Those numbers are oddly specific, but anyway
transform.rotation = Quaternion.Euler(x, y, z) is how you assign a new rotation with angles in degrees
i know there is more effective ways i wanna make how i know work first
probably putting them in a diff tilemap
how im new
As transform.rotation uses a Quaternion to represent a rotation (which does not store angles in degrees), you first need to convert those angles to a Quaternion. That's what Quaternion.Euler does. Euler angles are angles in degrees.
it dont work
why not
i dont know how to do it it gave errors
how can i balance my physics based movement code so it feels snappy? right now my character is sliding around a bunch and the gravity is very low for some reason so it doesnt feel very responsive
ah yes, it gave errors. and we're supposed to know what those errors are?
Hey guys, I have 2 scenes. in the first scene I have the player on the hierarchy always. and in the second scene I want to be able to access that player. how can I do that? I tried on the second scene assigning on the inspector the player prefab as serializedField Player player; but its not working. Is there a method to fetch things on the other scene?
singleton
could you just help and show how the script looks like mine looks like TilemapRenderer.SortOrder = 1.
This + a call to DontDestroyOnLoad() to persist the player through scene changes
you need to reference an instance of the tilemap renderer, it is not a static property.
how to get a reference: https://unity.huh.how/references
i dont know how to script c++
and for future reference, share your errors. don't expect others to just immediately know what they are (even though in this case I did)
okay, but how about c# which is what you should be using for unity
if you dont mind can you tone it down to simpleton explaination. Just i wanna understand it instead of just using it
dam
and if you don't understand how to code, there are beginner courses pinned in this channel
It's the simplest explanation. Quaternions are really complex objects, and unless you want brain damage you definitely should not look up Wikipedia's page on quaternions
loll alright thx tho
ik how to script just not in c#
then start with the beginner c# courses pinned in this channel
anything on this?
why not just multiply/divide its localScale by 2?
with something like image.rectTransform.localScale = image.rectTransform.localScale * 2;?
yeah so instead of a = a +b
you can just do a+=b
ohh I only ever encountered a++ for incrementing
it works sure, it's identical. To avoid floating point precision issues I'd probably do something like this though:
Vector3 originalScale;
void Awake() => originalScale = image.transform.localScale;
void Shrink() {
image.transform.localScale = originalScale / 2;
}
void Normal() {
image.transform.localScale = originalScale;
}
void Grow() {
image.transform.localSale = originalScale * 2;
}
yea much better than dealing with transform values
Hi ! I have a some problem with my code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerInputManager : MonoBehaviour
{
public static PlayerInputManager instance;
PlayerControls playerControls;
[SerializeField] Vector2 movementInput;
private void Awake()
{
if(instance == null)
{
instance = this;
}
else
{
Destroy(gameObject);
}
}
private void Start()
{
DontDestroyOnLoad(gameObject);
SceneManager.activeSceneChanged += OnSceneChange;
instance.enabled = false;
}
private void OnSceneChange(Scene oldScene, Scene newScene)
{
if (newScene.buildIndex == WorldSaveGameManager.instance.GetWorldSceneIndex())
{
instance.enabled = true;
}
else
{
instance.enabled = false;
}
}
private void OnEnable()
{
if(playerControls == null)
{
playerControls = new PlayerControls();
playerControls.PlayerMovement.Movement.performed += i => movementInput = i.ReadValue<Vector2>();
}
playerControls.Enable();
}
private void OnDestroy()
{
SceneManager.activeSceneChanged -= OnSceneChange;
}
}
and this is my error :
Type 'PlayerInputManager' already defines member called 'OnDestroy' with the same parameter types
you have two scripts with the same name
oh..
not only that but PlayerInputManager is a bad name in the first place because Unity's input system already has such a class, which will be confusing
ok ok i'll fix that
i have no idea what this is telling me. i've looked over my code and compared it to what i was following and cannot tell what i did wrong
lemme go grab screen shots and then a copy of my code
you cannot subtract arrays
i'm sure its a syntax or spelling error somewhere but i cannot see it
configure your !IDE
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
i'm not trying to subtract them, i don't think
you are, but you don't mean to
in what way? is it because zero is typed instead of numerical?
no, configure vs code and it will underline the line with the error and maybe you'll see your mistake
configure it how? i had VS installed for coding class already and it doesnt show me an error
installing it isn't enough
its as good as a text editor right now
i already have SKD's installed from doing coding with C#
doesn't matter Unity has their own workload
and many other coding languages so it should be fine
configuration is laid out in the link, they are very important steps
they are particular to unity
other languages != unity
"it should be fine"
and yet it's clearly not providing proper syntax highlighting and error underlines. go through the relevant steps linked by the bot
your issue is literally caused by a typo that a properly configured IDE will point out to you
ahh so thats what it means, i cant just use whatever native language unity uses without "extras" to help it run
Unity has no native language
its just C#
but C# configuration for unity is different
because unity uses old ass .net
Hi ! idk where to post this so i post here. This is the code of my script (nothing in it)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
}
When i'm trying to put the script to the component of my player, this is the "error" i'm having
(ofc if i didn't post this in the good place just tell me and i will delete this message)
do you have any compile errors?
file doesnt match class name
also that
where is console window lmfao
No error
man that layout is wack, i didn't even notice the console under the hierarchy lmao
fr
I thought mine was bad , turns out im wrong haha
as bad as mine
nah if it threw me off too its bad xD
anyway your file must always match class
mycoolfile.cs
public class mycoolfile
ofc don't use lowercaps cause its nasty
mostly a question about convention instead of an actual problem.
I have a scriptable object CharacterData and another one called CharacterLibrary to make getting data from specific characters easier.
in CharacterData I have methods GetPortrait() and GetAudioProfile().
would it be smart to give the CharacterLibrary methods GetCharacterPortrait() and GetCharacterAudioProfile to use these get methods from the library?
or should I just do GetCharacter().GetPortrait() in my code?
yes, and make sure to save it
yes, thanks to all !!
honestly arguments could be made for either way. I'd personally say make the Portrait and AudioProfile properties on the CharacterData class instead of using getter methods (since properties basically make those obsolete)
I'm trying to make a connection with MySql to store the scores in a DB, but I'm having difficulty installing the MySQL plugin in the project. So far I have added the .dll to the assets and changed the API Compatibility Level to .NET Framework
you have to make sure you got the compatible dll
also why not SQLite plugin
SQLite is dope
my bad I abstracted the methods, they take in an Emotion enum which is used as a key to get the values from a list
the database better be local
should never have connections to a database in your client/game
i'm still of the opinion that you should put those methods on the CharacterData class, why should the library that contains the list of that data care about the individual pieces of data on each one?
of course if you prefer it on the library class you could do that if you prefer. it really all comes down to which you think would be better for your workflow
It's actually a semester project, I'm using a DB on localhost so that the computers on the network can connect to the DB
my thoughts on this are as follows: think of your CharacterLibrary as an actual library full of books. the books are you individual CharacterData instances. you wouldn't go to your local library and ask it for the contents of a specific book, you'd get the book and get the contents of the book from the book itself
I could see either way working, though I agree that the library shouldn't care about the properties of data holders so I'll keep the methods in the character data 
using UnityEngine;
public class Movement : MonoBehaviour
{
// Data
public Animator animator;
public float moveSpeed = 5f;
public Rigidbody2D rb;
public Vector2 movement;
Vector2 lastMovement;
public bool isCasting = false;
void Update()
{
// Get input for movement
float horizontalInput = Input.GetAxisRaw("Horizontal");
float verticalInput = Input.GetAxisRaw("Vertical");
// Calculate movement vector
movement = new Vector2(horizontalInput, verticalInput).normalized;
// Check if the character is moving
bool isMoving = (movement.magnitude != 0);
// Set animator parameters for movement
animator.SetFloat("Horizontal", horizontalInput);
animator.SetFloat("Vertical", verticalInput);
animator.SetFloat("Speed", movement.sqrMagnitude);
// Set facing direction when idle
if (!isMoving)
{
// Use the last movement direction when idle
animator.SetFloat("IdleHorizontal", lastMovement.x);
animator.SetFloat("IdleVertical", lastMovement.y);
}
else
{
// Update last movement when moving
lastMovement = movement;
}
}
void FixedUpdate()
{
// Move the character
rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
}
}
feel like there's something wrong with this, its attached to an animator that gets the horizontal and vertical axis in wasd movement, and its saving the axis to display the right idle animation too when the character is still, but i feel like its wrong
!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.
large code should be links
well i followed the instructions and downloaded Cs and the unity vs code, even changed unity's preferences to match but now its telling me i don't have .NET
restart the computer if you just installed it and it's still not recognizing that you have the sdk
mk, restart it is. brb
instead of rb.MovePosition() I'd recommend rb.velocity = ... or rb.AddForce()
trying to make a procedural gen i see
@steep mist if after this doesn't work, try to reinstall the .net 8 SDK manually from the website
had to do this recently , somehow vscode wasnt downloading it
wrong person
my bad yes
np np
thanks i've done that, still somehow doesn't fix my issue :/
sorry can't help with animator hell, I don't use it that way xD I just do animator.Play() most of the time
oh, thank you!
i feel like the animator is for ""2d"" games where you animate everything separately (limbs and such)
But its completely overkill for wasd 2d games that use diffrent simple animations.
that could be, because it keeps giving me this
it probably doesnt help that i've installed unity onto another drive to save space. if i need to i'll install .net8 directly to that drive and that project
well you restarted? already ?
mhm, got a newish gaming laptop its pretty quick
dont think it matters for Vscode. install the .net 8 sdk and restart
the animator is nice for blending using rigs yea, sprite animations don't need that functionality so .Play should be fine 9/10 times
the issue is its not loading the Solution
once it opens the solution then you know it works
im just using it to track wether my character is moving top, down left or right, am i complicating my life tho?
yes
after you install .net You'd have to try regen project files in Unity again (assuming you did install the update for the VSEditor package) @steep mist
amazing also kinda pain T-T
i spent so much time in it today
trying to make it work for sprites reee
regenerate the files how?
you'll see the option in one of the locations you had to do something when configuring vs code 😉
also this is the correct one right?
yes
i'm using visual studio code which seems to have a slightly different set up
at least from visual studio
a different set up to what? vs code? because i was referring to the instructions for vs code
it does but it should work
but its very picky about it
Remove the Visual Studio Code Editor package from there
I'd say, do something like this:
public enum Directions
{
North,
East,
South,
West
}
[SerializeField] private Directions direction
public Directions Direction
{
get
{
return direction;
}
set
{
if(direction != value)
{
direction = value;
anim.Play(direction.ToString());
}
}
}
it's already removed, it doesn't have a check
very quick dumb question
i have a transform.position
I want that point + 2 on y
what i should write?
||+new vector3(0,2,0);||
what do you think you should write for that?
Ah, that's in registry. So used to people showing their current assets
well what navarone said lol
i was wandering if there is a way other then adding a new vector3
why
just for not create a new one and just add 2 to the previous location
i did when i realized it was the wrong one
a new one ? is just a struct nothing wrong with new()
its 3 floats but fancy
oh wait true
It's a struct; you have to assign the whole thing . . .
my b
Nah yeah, boxfriend pointed it out. Sorry for the confusion
#💻┃code-beginner message
your two options for adding something to a single axis on a Vector3 property are what navarone showed, and copying the vector, adding to the Y axis on the copy, then assigning the copy back to the property
https://unity.huh.how/compiler-errors/cs1612
well i think then i've done everything, but it still wont debug in vs code
you don't need to be using the debugger for this, you just need it configured to see your simple typo
but if you cannot get vs code configured, then consider switching to a real IDE that is less likely to be fucked up like visual studio
oh also, did you regenerate project files?
i don't know tbh, apparently there was instructions somewhere in all that install that tells me how to do that.
i didn't see it so idk
go through all of the steps again and you'll see it if you've done it correctly
the big button that said Regeenrate Project Files in the preferences step
by regenerate does that mean open the files associated with the project in vs code
no
there is a button that literally says Regenerate Project Files
and i am intentionally not telling you where it is because you've clearly missed steps in the configuration so you need to go through it
ill delete my msg 🙂
Debug.DrawRay(transform.position, (transform.position + new vector3(0, 2, 0)) , Color.red);
gives me that can't find the vector3 namespace 🤨
📃 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.
spell it correctly
your parameters for your Debug.DrawRay are also incorrect, the second parameter takes the direction and length, not the end point
dont copy spelling mistakes 🙂
ooh i see it now, the web page given didnt say anything about it though it probably should have added that in
"for users who already have scripts press regenerate"
Hi so i have this script i just dont know how i should like hold the object I am making like a gravity / physics tool and rn i am trying to make it so you can pickup an object and rotate it when holding CTRL and move it in and out using scroll wheel but rn i am stuck on the pickup thing idk how to make it pickup the object i have a PickupPoint Empty Game Object infront of my player here is my script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GravityTool : MonoBehaviour
{
[SerializeField] private Camera playercam;
[SerializeField] private Transform holdPos;
[SerializeField] private LayerMask pickupLayer;
[SerializeField] private float pickupRange;
private Rigidbody currentObj;
private void Update()
{
Ray ray = playercam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
RaycastHit hit;
if (Input.GetKeyDown(KeyCode.E))
{
if (Physics.Raycast(ray, out hit, pickupRange, pickupLayer))
{
currentObj = hit.rigidbody;
currentObj.useGravity = true;
}
}
}
}
yeah they assume everything goes right @steep mist
or something like that
the doc says that the second parameter is the end
where does it say that?
hint: it doesn't
https://docs.unity3d.com/ScriptReference/Debug.DrawRay.html
Direction and length of the ray.
Declaration
public static void DrawLine(Vector3 start, Vector3 end, Color color = Color.white, float duration = 0.0f, bool depthTest = true);
That's DrawLine
this is a different method
Not DrawRay
how will i know if this "worked"? i pressed it and no icon indicated it did anything
restart vs code after regenerating and if you've got everything set up correctly you'll finally see your typo underlined in red
alrighty
!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.
still no red line. i think i'll save, close and re open the whole project and if need be do another restart
Can someone help me here?
you probably want to disable gravity when picking it up, rather than trying to enable it again. you should probably also be parenting the picked up object to the PickupPoint object
yea true
heey, i need help... please... any ideas on why does the jump method is not getting executed: https://gdl.space/sipokobeni.cs
you regen project files and open script via unity ?
open the Output tab
I've checked that the condition it's right...
how have you confirmed that the condition is correct and that it is evaluating to true?
I making a claw machine game and I’m using the timeline to drop and raise the claw, how can I make the animation just change the y axis instead of setting the claws position to the x and Z positions in the recorded timeline?
Show where you set hasCollisioned.
Also, put debugs in there
Worked i did not think about doing that
eh would not use animations for this (moving position)
also ur in a code channel
yeah, i made it public... and all seems to be right with that
huh?
also the sound correctly sounds... so that's like a log
don't make assumptions about what is happening. you need to verify
finally all that to realize it was not an = sign
yep
at least i finally have debugging set up correct
its working now ?
yeppers
good!
finally! woo
and now you will be much less likely to make simple typos like that in the future
precisely
now VSCode is somewhat of an IDE and not just text editor
Comment out the line where you set velocity to 0
As a test
i mean tbf it was and IDE when i was learning Node JS and others. but now it is for UNITY
that shouldn't be an issue. i do the same thing in my flappy bird clone to ensure that each jump applies the same velocity from the same amount of force
lol flarpy birb
i'd bet either their variable for the impulse is 0 or their rb is kinematic or something simple like that
unless the condition is not true
imma get back to it, goodluck with gravity
it was a joke but even still . Node on VSCode stinks
JS and its dynamically typed code arg..
at least use Typescript xD
Yeah, I was just wanting to see if it would even shift over time.
i tried it... 😦
that's not the prob
have you added any useful logs or are you just making assumptions about your code?
Can you show the inspector for the bird, and put some logs in?
Playing the sound isn't enough
a minute ago it worked correctly... it sounds weird hehe, but i don't know what i have touched
let me first check what @slender nymph said me in here
here
thanks! T-T
Showing the inspector would be what boxfriend wanted to see for both those things... post it
The third would need a log
where is the rigidbody
Impulse is pretty low too
Depending on the mass and gravity
every time u change the Direction variable it should update the animation playing
Eh, should be fine value to only go a little.
i also suppose it could be some interfering canvas... but i disabled them all and it was not the problem
What would the canvas have to do with it?
have you added any useful logs to determine that the code is being executed?
nono, i mean that some canvas could be betwen my finger and the screen...
like this one?
that is not useful in any sense of the word
definetly that log works
You can actually put VALUES inside debug log. Just doing a word is not really great
The bird is the word . . .
yes, i have no doubt that useless log prints. try printing some useful information, such as the condition you are checking
ok... but far away that, this could be usefull to you... that's the first jump... and it works
but then jump stops working
problem is what if a player decides to press W and A, or opposite directions like W and S
If you're not going to take the advice that will help us determine the source of the issue then I'm not going to help you anymore
Sorry, i expressed wrong myself... i'm doing it rn... i appreciate so much your help
So i am thinking of making it so once you click a station character faces that specific stations and shoots out to it. Having hard time with the orientation where it faces selected station. So i was wondering what do you guys think i need to learn to accomplish this, not how but what
- get the position of the selected station so it can face it basically
do i better put it inside?
Get the direction from the player to the object, and assign that to the player's transform.right
Direction is just (endPosition - startPosition).normalized
You're only printing one part of the condition
but that's wrong... how could i print the input action?
or you mean like this?
Ohh ok thx
What does .normalized do
those are both logs printed
add a none state, or you can add all animation states into it and rename it from directions to animationstates
thanks! ❤️
not quite, but at least with the second log you know that the code is being executed
so if the object is not jumping then either your force is too low, or something else (like controlling the position via animation) is preventing it from jumping
in your case it wouldn't actually be necessary. but it makes the length of a vector 1
Sets the vectors length to 1
oh ok
Hi, I have a syntax error that I'm trying to find for 2 hours now, idk if i can post the code here
It's not the force...
!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.
also if you cannot see it underlined in red in your !IDE then you need to get it configured
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
i've tried configured the IDE but i have to much errors
so then what is the issue? you're not bothering to show what is happening when it isn't working
if you need help with getting your IDE configured, then you need to maybe provide some details about what exactly you are struggling with
Ok i'll try tomorrow
okay well then you will get help with your syntax errors tomorrow
im haivng some issues thats its going to make me punch the f*** screen lmao
for some reason the buttons are not working
its interactable, its on the canva, theres nothing on top of the button
i really think the Unity is bugged, i already restarted the PC and nothing. Really strange... im getting so pissed off about this lmao
why this is happening..
one more thing so i have the script in player.
is it just transform.right = direction;
or transform.right is executed differently
Don't cross post
Also, make a new button, don't change anything and check if that's pressable
From there just change one thing after another to see what's the issue
Idk if the 4.6 scale doesn't have to do something with this
sorry bro i didnt know if that was the general code or begginer so i posted both lmao
It's neither probably since it's not code, lol
But as I said, make a fresh new button, which should work out of the box
If that's not pressable then there's something blocking it
yeah, i made a new button, didnt change a thing
still not clickabl
the canva is at 5 layer, how its blocked?
blocked from what?
Something else in the scene, but if there's nothing there then idk
Just made a button on layer 5 in my project and it works without any issues
I might be missing something tho since I rarely use the built-in button
can someone see where i went wrong in this code. its supposed to render 6 sides of a cube but its only rendering one side
Try disabling everything else in the scene besides the button or wait for someone else to help you
yeah, i created a new scene and tested and its all good too
for some reason its that scene the problem
Then probably something in your scene is "blocking" your press
gonna do it
good call
disable one thing after another
or disable everything and bring back one thing after another
that should give you the answer
bruh idk wth is going on lmao i removed everything and still not working, its some canva config for sure
maybe the Scale with screen size?
Not sure, I'm not that good with UI
Try playing around with settings / compare it to a fresh new canvas
@blissful heart Do you have an EventSystem? I dont see one in your hierarchy.
Damn bro
you are goddamn right
I got one now and its working
Thanks a lot @modest dust for the help and @scenic cipher
You're welcome
i guess i removed the eventsystem by accident dk
Ah yes, EventSystem, makes sense
It happens
now its time for 100x ctrl+z and continue progress hehe
Finally it was just a silly thing... I hadn't dragged an object to the inspector lol... Thankss for your time... and for your patience too
i know that feel...
I was brokening my head trying to think what could be happenning hehe
haha yeah just like me rn
i've been like 1h trying to click the f button
and it was just the eventsystem lmao
this discord helps a lot
Do not ignore the errors in your console
Now and then i'll check that at first hehe
Is possible to turn on / off avatar mask parts from script?
why doesnt this work?
it still prints the object the script is on to the console
i did this
so what, just cache the owner
what
I dont see where your printing in your code, though maybe you should print before your first if-statement, you could also try just disabling the collider on gameObject before you do your overlap cast so you shouldnt need a self-check that way
it works not its fine
How could I make scaling a parent object not affect its child object?
having issues with netcode for gameobjects and lobbies, I don't understand how to resolve this error? ```public async void JoinLobbyByCode(string lobbyCode)
{
try
{
player = playerNameText.text;
JoinLobbyByCodeOptions joinLobbyByCodeOptions = new JoinLobbyByCodeOptions
{
Player = new Player
{
Data = new Dictionary<string, PlayerDataObject>
{
"PlayerName", new PlayerDataObject(PlayerDataObject.VisibilityOptions.Member, player)
}
}
};
Lobby joinedLobby = await Lobbies.Instance.JoinLobbyByCodeAsync(lobbyCode, joinLobbyByCodeOptions);
Debug.Log("Joined Lobby with code" + lobbyCode);
} catch (LobbyServiceException e)
{
Debug.Log(e);
}
}```
You don't
these beginners 🤦🏽
GameObject obstaclePrefab = obstacles[Random.Range(0, obstacles.Length)];
float colliderHeight = obstaclePrefab.GetComponent<BoxCollider2D>().bounds.size.y;
Does anyone have any idea why this is returning only zero? My object has a proper boxCollider2d set up
https://docs.unity3d.com/ScriptReference/Collider2D-bounds.html
Note that this will be an empty bounding box if the collider is disabled or the game object is inactive.
I couldn't find this resource helpful for my specific issue, I understand how dictionaries work at a base level, however my code seems to still error, I am following along with a codemonkey video on Unity Lobbies and yet even when altering the variable names to be exact copies it still presents the error message
Ahh. Do i nede to refrence the bound size after i instance it?
your syntax for the collection initializer is wrong. read the page to see the correct syntax
yes
Hello, I have this sprite, which, as you can see, has a gun that's not in the center of the sprite (along the y axis). I currently have this code to rotate my player towards the mouse cursor, but as you might notice, it rotates the player's y axis towards the mouse, not the gun. I want the gun to point towards the mouse.
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 direction = mousePos - transform.position + new Vector3(0, 0, 10);
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg - 90;
transform.rotation = Quaternion.RotateTowards(
transform.rotation, Quaternion.AngleAxis(angle, Vector3.forward).normalized, rotationSpeed * Time.deltaTime
);
ok the sprite is much tinier than I expected oops >_> Well, he's holding the gun to the right of his head
The simplest solution would be to fix the sprite to point up or right.
I'm currently trying to update the object texture but it's not working for some reason
I believe the property returns a copy of the material. Cache the copy, modify it and reassign it back to the property?
i found out where the issue was, the "SetTexture" method is for meshes only if i'm not mistaken
SetTexture work for 3d Meshes and Sprite.Create work for 2d sprites
i need help with something
Ok
Can't help without knowing what you need help with. But we would be happy to
sorry
Wrong thing
Guys, I'm building a character movement script for my 2D platform game. I got this code right here. I attached this script to my character, and the variable isGrounded always true. How can I fix it?
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Unity.VisualScripting;
using UnityEngine;
public class Charater_Moving : MonoBehaviour
{
private Rigidbody2D player; //Get the Charater Rigidbody for movement
//Moving
public float moveSpeed = 5f;
public float jumpForce = 5f;
//Jumping
public Transform groundCheck;
public LayerMask groundLayer;
public float groundCheckRadius = 0.2f;
private bool isGrounded;
private int extraJumps;
public int extraJumpsValue = 1;
private void Start()
{
player = GetComponent<Rigidbody2D>();
extraJumps = extraJumpsValue;
}
private void Update()
{
// Handle left/right movement
float moveX = Input.GetAxis("Horizontal");
player.velocity = new Vector2(moveX * moveSpeed, player.velocity.y);
// Check isGrounded
isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, groundLayer);
Debug.Log(isGrounded);
//Handle Jumping
if (Input.GetKeyDown(KeyCode.Space) && (isGrounded == true || extraJumps > 0))
{
player.velocity = new Vector2(player.velocity.x, jumpForce);
if(isGrounded == false) extraJumps--;
}
}
}
What are you trying to do ?
Oh
Is the player accidentally on the ground layer?
I don't know. The character can jump and land on the "Ground" Layer, but because isGrounded is always True, my character can always jump when the Space bar is pressed repeatedly instead of 2 jumps and fall to the ground
You should easily be able to look. Check what layers are selected in your "groundLayer" variable in the inspector. Then look at the player and see what layer it is on.
And where is the groundCheck transform?
check if player's layer isn't set to "groundLayer"
I have the groundCheck
It might not be CALLED groundLayer, that is the layermask variable name
I know, I see that. I wanted to know where it is (meaning its position)
The player is not set to groundLayer
i know, the player's layer might be same as the ground layer
Best to just take a screenshot of the players inspector and show it
ok
I know. That was what I suggested. I just wanted to make sure Duy didn't get confused thinking the layer had to actually be named that.
No worries
You're moving a child
Ground check is not moving with the player
And stays on the ground
you should move the rigidbody2d and character_moving from "Captain [Demo]" to captain
Thus you can jump infinitely
Well, at LEAST move the rigidbody. But far more crucially, move the "Character_Moving" to Captain
That is the script actually moving
why when i drag the game object disapear in the game tab but in scene tab its still visible and moved
oh wait wrong code
How do you mean it disappears in the game Tab?
Just out of view or invisible?
are you working in 2d or 3d?
But, isn't there something we could do, like creating an empty and placing it on the muzzle of the gun, and making sure that it's this empty that rotates towards the cursor?
What is the position after dragging?
Check out the objects position. Likely it's at the camera position (Z)
You can place your visuals as a child of the controller and add rotation offset if that's what you mean. But ideally you want your assets standardized.
Which might be at -10
trying adding the middle line
ah i see now its out of camera z position
how do i like activate a animatoroverride
Maybe just do cs var mousePos = ... mousePos.z = 0; transform.position = mousePos;
@summer stump @queen adder I just deleted Rigidbody2D and Charater_Moving Component from the Captain[Demo] and added them again to Captain, but the problem still exits
i just tested your code and it's working fine, the issue is with your player prefab
delete everything and then add an empty gameobject, add your moving script and a rigidbody2d to it
add a square object as a child to it and add a boxcollider2d to it
add another empty gameobject and this should be your groundcheck
Show the groundCheck object
Or just do what Moe said. That would work too
The issue is with the GameObject setup, not the code
Will do
Oh yeah, the seconde object is the fall detecor I added recently right?
that means the charater will have 2 child: groundCheck and FallDetector, right?
Moe did not say add fallDetector
Leave that off for now
Shaders are programs for the GPU telling it how to render something.
okay
does someone have a good reference for 2d player movement in unity
Yeah plenty.
Unity.learn.com has good a one in the pathways
no need for fall detector, the groundCheck should do the trick, when you add it, lower it same as the picture here
ok ty
The White square belongs to the "Player" or the "Square"?
it's in charge for the sprite and collision
- empty gameobject (add rigidbody2d and movement script)
Square2d (add BoxCollision2d)
GroundCheck
discord is missing with me
How would I make a script for a 3d game thats supposed to move the camera and follow my player using Time.deltatime?
cameraTransform.position = playerTransform.position + offsetVector;
The player would be the one to use deltaTime
Or just use cinemachine
i work on games for virtual reality which means i make games that use shaders as in water shaders
What are you asking for here then?
All games use shaders.
Ok... tell us more though. Because that is super vague. All games use many kinds of shaders.
All I can say is look on the asset store or google it 🤷♂️
Guys, it still doesn't work. I hope I didn't miss something.
Write them.
No no like if u make games on vr as in ur making water and u need to shade them which i am talking abt shading the color
In vr or any game. It is irrelevant that it is vr...
So, again, look on the asset store, google it, or as dlich said, write it
that's the right order, can you select the "GroundCheck" and screenshot?
shaders are programs that tells the GPU how to draw every pixel on your screen
This is it
screenshot the scene window
There you go
it's in the right place, select player and also screenshot
The player and Captain (Demo)
it should be working fine, check if your ground has the "Ground" Layer
yeah, i think it's not the player's issue anymore
But the ground has the "Ground" Layer already...
then what's the issue? infinite jump?
Yeah, infinite jump
The isGrounded variable is always true -> infinite jump
you sent script already ?
i hope that's not a border of a collider is it xD
when in doubt always debug your casts
I was about to say that! That looks kinda green!
yeah weird why does ground have box collider ?
tilemap collider already takes care of that
anyway outta print the results of what ur hitting just in case
Is that box collider (assuming that is what Moe pointed out) a trigger? The check will still register a hit on that afaik
if you have a colliderbox2d set to trigger in the background and is component of the ground, your circle is gonna overlap with it, true removing that component
i always use this one when workng with 2D
public static int OverlapCircle(Vector2 point, float radius, ContactFilter2D contactFilter, Collider2D[] results); just so I can print results
Got damn it, it's green :)))))
it has box collider :)))
just disable it and the isGrounded works properly now.
also, your code is not gonna double jump
remove it and try this one below
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Unity.VisualScripting;
using UnityEngine;
public class tt : MonoBehaviour
{
private Rigidbody2D player; //Get the Charater Rigidbody for movement
//Moving
public float moveSpeed = 5f;
public float jumpForce = 5f;
//Jumping
public Transform groundCheck;
public LayerMask groundLayer;
public float groundCheckRadius = 0.2f;
private bool isGrounded;
private int extraJumps;
public int extraJumpsValue = 1;
private void Start()
{
player = GetComponent<Rigidbody2D>();
}
private void Update()
{
// Handle left/right movement
float moveX = Input.GetAxis("Horizontal");
player.velocity = new Vector2(moveX * moveSpeed, player.velocity.y);
// Check isGrounded
isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, groundLayer);
Debug.Log(isGrounded);
if(isGrounded) extraJumps = extraJumpsValue;
//Handle Jumping
if (Input.GetKeyDown(KeyCode.Space) && (isGrounded == true || extraJumps > 0))
{
player.velocity = new Vector2(player.velocity.x, jumpForce);
if (isGrounded == false) extraJumps--;
}
}
}```
you need to reset the extraJumps when ever you get back on the ground
!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.
Just as a tip, format code like this
```cs
//code here
```
So it looks like this
public class MyStuff
{
void DoThing() { }
}
Edit: Oh, too slow, as always
haha, it's the effort that counts
How can I fix it guys?
you probably want to start by constraining the Z axis rotation on your rigidbody. beyond that we probably need more info
Thanks! I forgot doing that one
Hello.
hey guys how can I save the color of an object when I am saving data using a method like that ```cs
public static void SavePlayer(Player player){
string path = Application.persistentDataPath + "/player.save";
PlayerData playerData = new PlayerData(player);
var savePlayerData = JsonUtility.ToJson(playerData);
File.WriteAllText(path, savePlayerData);
}```
same way you save PlayerData
I need some advice regarding my code. Basically I have a text file that had like 4 million words in it I wrote along the years, but that's besides the point. I have a button that displays a random chunk of it, but it sometimes freezes the game or crashes it the first time you press it but not consecutive times. I have the text preloaded, or had it but the problem persisted. (I didn't remove the preloading thingy) I haven't tested it yet but I added a new line of code: chunkSize and set it to 1000 (lines) or something like that.
Will this fix my problem or should I split the text in multiple files?
my player data now: ```cs
[System.Serializable]
public class PlayerData{
public int coins;
public int movementSpeedSkillLevel;
public int movemenSpeedSkillValue;
public float playerSpeed;
public PlayerData(Player player){
coins = player.coins;
movementSpeedSkillLevel = player.movementSpeedSkillLevel;
movemenSpeedSkillValue = player.movemenSpeedSkillValue;
playerSpeed = player.PlayerSpeedControl();
}
}``` its working fine.. but here I would need to fetch information from a specific component in a specific object to fetch the color. I will be able to do that here?
You technically won't have the same exact object
just use the values to the object from this file
The objects I need to save the color are inside the player script: cs [SerializeField] private GameObject[] _movementSpeedSkills;
wdym Gameobject don't have color no?
also GameObject is very much not needed, use directly whatever script these objects are
you can just save it separately if the color is not related to this data, or have some bigger class/struct which holds everything (references to the existing classes) thats saved
all my objects that load stuff have an an interface of ILoadData , I have an event that calls all the LoadData types
have u profiled which part is actually freezing the game? the profiler with "deep profile" on should tell you exactly whats taking the most time. Im not sure what you mean having the text preloaded though, what is preloading in this case
hmm ok, well never used interface will need to check stuff about it
think of it like a modular "class" that adds obligation to your scripts to implement a method/property
because its not inheritance you can add many interfaces on 1 script
ahh ok yeah I think i remember about it now, had it long ago during a bootcamp.. true. completly forgot about it, will check it out. thank you!
I'm still new to coding, mainly trial and error/ asking people on stackoverflow, but this thing is loading the text in void start:
StartCoroutine(LoadTextFile());
they're are very powerful, yeah def go over them as well. Pretty handy in almost anything but a load save system as well
hmm interesting. Tomorrow I will study this.. thank you!
The strange thing is that it's only happening in the built version of the game but not in the editor.
you should look into the profiler with the cpu section, use the graph to see where the spikes are then look at the hierarchy of that frame
how are you loading the text?
probably putting all the lines in memory at once lol
use async also for long running operations
Can I post the whole code? Is it allowed?
📃 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.
hmm a split?
Yes, it's formatted like this:
First sentence.
Second sentence.
Don't ask why, I messed up the formatting in the file.
haven't used textasset too much but for files I use StreamReader.ReadLine
much more efficent
pretty sure textasset can be loaded the same no ?
why my ray not hitting the slot? it have slot tag with collider
Yes. But I don't think that's the main issue. I'll try looking in the profiler like bawsi said.
Debug.Log it
debuged it seem to hit box game object and logit out but not the canvas slot object
wdym canvas objects should not use colliders anyway
use EventSystem raycast
is EventSystem raycast use specificly for ui?
yeah its literally meant for it
you can also just use IPointer interface
whats that?
https://docs.unity3d.com/2018.3/Documentation/ScriptReference/EventSystems.IEventSystemHandler.html
Left side (IPointerClickHandler) is the most common one
is a scene that is additively loaded running on a different thread from the first scene?
I do not believe so. At the least, all code running in that scene is on the main thread
don't think so as most of code in unity runs on the main thread
oh dang
ah im too slow
JOBS 🙂
jobs D:
i thought i could at least run a scene additively on a different thread so that my loading screen doesnt hang
i use a little timer at the end with a black fader
i need the scene to run on a different thread all the time because when I load my main scene it runs an expensive operation
i should probably optimise my code
async could potentially be sufficient ofc you can always move it to a multi-thread operation if you must
Then you have to do jobs. Or tasks maybe.
How would unity know what is thread safe otherwise?
the process involves instantiating objects which jobs doesnt like
but come to think of it i should not instantiate 100,000 game objects
time to convert to ECS
Can you spread the work over multiple frames?
Oh daaang. Yeah .. that is a lot
just read on this, its perfect actl i will look into it
expensive operation, 100,000 game objects
loading screen doesnt hang
the solution would be either make a prettier loading screen or completely do something else. theres not really a solution that'll do what you want, unless you can massively reduce what you initially spawn
Ecs or fake a lot of the objects by directly drawing them in the gpu. Do they NEED to be gameobjects?
not really I can convert my code to use structs
drawing them directly in the gpu should be fine I just need to get tmpro's meshes to work with me
if I use the default cube mesh provided by unity is it supported by gpu instancing?
oh it does
Ive tried many things so I'll ask here, I need to check if a target is facing another. Not if a target is looking at the other objects front. I simply need to check if its at a minimum angle to trigger an attack.
Vector3.Angle/Vector3.Dot
What have you tried?
Looks correct.
float dotProd = Vector3.Dot(dirFromAtoB, transform.forward);```
Its getting wierd values ill try to debug and show it
That also looks correct
Then it goes to 40 for some reason
the 40 is when the navmesh agent stops rotating meaning its looking at the target so it no longer needs to rotate
the number should be decreasing to 0 right
It won't decrease to 0 if you tell it to stop rotating at angle 40
right but the way the value is going is odd, the navmesh agent over time rotates toward the target
this is 60
27
40
the last pic (40) is when it officially is fascing the target
Don't expect me to know what's going on here. Like who's the transform and who's the target
ah the left is the transform and the capsule is the target
the cube in the front of the left transform represents the head
the rotation is done by navmeshagent by default it rotates towards its destination, in this case the target transform
Maybe you want to check the Y angle only?
float angle = Mathf.Abs(Vector3.SignedAngle((target.position - transform.position), transform.forward, Vector3.up));
yea
giving that a shot thanks
still the same problem
im going to try this in another scene and manually rotate it myself
So the problem is that it says 40 angle when it is directly facing towards it (and angle should be ~0)?
@abstract finch Try drawing the two directions to debug it
right its strange because it decreases then goes back up for no reason
There is a reason, you just haven't debugged it to find out
Draw the two directions that you pass into angle/signedangle
how would I do that?
you mean debug to get the values of the signed angle and transform forward?
Debug.DrawLine/DrawRay, for example
the code works fine in the test scene when i rotate the object myself
ok i found out the issue its because the enemy transform is a lower Y level then the target
so what I will do is create a new Vector3 with the same y as the target and it should work
Huh, that's exactly why I suggested to use only Y angle. Did you even try it? 🤔
This will work too.
I didnt know how the code worked tbh then common sense hit me
signedV3.y = 0;
float angle = Mathf.Abs(Vector3.SignedAngle(signedV3, transform.forward, Vector3.up));
Debug.Log(angle);```
Either do what I said here ^
Or this cs Vector3 dir = target.position - transform.position; Vector3 forward = transform.forward; dir.y = 0f; forward.y = 0f; float angle = Vector3.Angle(dir, forward);
is the one you provided more versatile?
because I plan to have flying enemies as well
the snippet above doesnt consider height, so flying enemies might have infinite vertical sight if you only compare the angle
got it thanks
The whole point was to not consider height. If you still want height to affect the angle, you might want to adjust the origins used for the direction (target.position - transform.position)
If it's a visibility check or something like that, you can ignore the height when the distance is below a certain threshold
Is there a quick way of getting an instance of the GameObject a Script is attached to? Currently I'm using a [SerializeField] attribute and then setting it to itself, which seems unnecessary
Simply gameObject
It is a MonoBehaviour property and will always exist because MB's always live on a game object
Oml of course it's that, thanks
Also, follow up
Is there any way to like, disable an empty (so the child objects go invis) without preventing event functions from being called?
So like, RN, I've grouped some buttons using an empty. They know when to disappear because they have a listener method. However, that listener method gets disabled along with the whole script annoyingly. Is there any way around this?
Oh, like disabling the child objects ig...
Yup, that works. Cool, thanks for reading my ramblings 😂
lol, how do I set this?
Equipment equipment = FindFirstObjectByType(FindObjectsInactive findObjectsInactive) <Equipment>();
I need it to return an inactive object too
if theres really only one of this object, where FindFirstObjectByType wouldnt have any side effects by 2 existing, just use the singleton pattern. You really shouldnt need to use the Find functions that often
yeah I found another way to get equipment 🙂
that code looks very off too, why is there 2 sets of ()
it should be FunctionName<Type>(params);
To answer your question, it would be FindFirstObjectByType<Equipment>(FindObjectsInactive.Include)
But yeah, avoid Find
yeah ik
I should really learn how to use singletons
but there's so many different ways to implement them
does C# have something in between discard (_ = await ...) and await?
I'd like my code to keep running, but I do want to make sure my Task is eventually finished
Why would you need to discard it then..?
there really isnt, you may see different ways online but most of them might be an all encompassing overkill solution or may be related to other fields of work. Some use the Find functions to ensure there is only 1 (and throw an error if theres more), but you can just Debug.LogError in the if statement of my example below. You really dont even need thread safety, because i think async/threading stuff isnt needed in most cases. I dont know any cases where you would want to use it tbh
Simplest way can just be
public class SomeClass : MonoBehaviour
{
static SomeClass instance;
public static SomeClass Instance => instance;
void Awake()
{
if (instance != null)
{
Destroy(gameObject);
return;
}
instance = this;
}
}
there is also a way to write it with generic classes, but its more so you dont write repeated code instead of actually needing a base class.
What're you refactoring?
making my character a singleton
Should there only be one?
Ensuring that ease of access isn't the sole reason to doing so
there's only one, it's in the scene and never destroyed/created
and I need to access it everywhere
Making the player a singleton doesn't sound like a great idea regardless of the circumstances. Maybe make it a property of a singleton game manager.
should be totally fine for my concept, it's not a game where you run around and do stuff
Usually the purpose of a Singleton is to prohibit the use of multiple instances of the object. They make good patterns for managers that observe other data. They're not a good pattern for use with objects that actually may need multiple instances - quite annoying to undo all of the constraints and dependencies of the ease-of-access instance field/property.
And changing the Singleton can have annoying after affects upon other classes
Something is going to have to spawn your player, so whatever spawns it can pass it to a singleton game manager easily. If your player already exists in scene, its simple, drag it in the inspector to the game manager
but here you told me to just use a singleton?
and the game manager being a singleton is still relevant, you havent really described what this is for so I cant recommend the entire best practices based off 1 line of code. I did find it weird that this was being done on a script called Equipment initially, but i cant really assume what its for
so I should have a gamemanager that is a singleton
to hold a reference to classes like character (which has equipment) to make it easily accessible?
a game manager makes more sense to be a singleton, because you wouldnt want multiple instances fighting over stuff. I cant really suggest much because i dont know what needs access to the player
so i put my item gameobject in the event trigger. the item is a physical object in the scene right now . can i still be able put an instance of the item game object in here in the future??
what instance in what future?
well for testing right now the item game object is in the scene im gonna start to instantiate the this item game object in the future, my question if i can still be able to use the event trigger component?
if you make it a prefab and instantiate the prefab then the new gameobject should have the triggers too yes
you mean i can just put the prefab in the event trigger component and it will work for the instance of the prefab?
ah thank you
eh no
well depends, it might work in your usecase
don't really know what ur trying to do
If you want to change the parameter of the event at runtime, a static trigger like that wouldn't work. Subscribe to the event in code.
An event assigned in the inspector would always invoke with the parameter you set in inspector.
ah i see
Fixed
Ok
Anyone here know how to make DOTween LookAt only change the Z rotation of an object?
how could i make it work with arrow keys aswell
***using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Block : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.A))
{
transform.position += new Vector3(-1, 0, 0);
}
else if(Input.GetKeyDown(KeyCode.D))
{
transform.position += new Vector3(1, 0, 0);
}
}
}***
if (Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow))
||
|| sorry
!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.
ty
got iy
Hi, does anyone know why i can't access a bool variable from another object?
I initialized it in 2 objects but i can access only from an object which has the same prefab
it needs to be public, but i can't understand why its working without public in planescript
Ah.
public means it can be accessed anywhere.
If you just leave it blank int some_class_var; it's implicitly private.
And when it's private, only the type itself can access it.
I'd prefer if you take a screenshot of the error code too.
!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.
I watched a GDC vid that was about an alternative way in handling quests where a quest is described in multiple states of statemachines in the game, the example given was the state of a commoner if they asked you to kill a wolf, getting impatient and being gone (going to solve it themselves) and the state of a wolf in the woods, if you've heard of it, if you've seen it and if you've killed it.
I'm thinking of a dynamic way of implementing this where the player has a list of states with an ID as to what state machine it belongs to and characters, monsters, places, etc. have those state machines and add to the list as soon as the player has exited the null state. I'm not sure how to implement this though.
I thought of using a list of enums for the state machine but that's not dynamic at all. what is the best way to handle this?
Mornin' all, I'm having a really weird issue that I can't figure out and it's bugging me. lol.
I'm cycling through a list of objects and for each object I need to find/assign it's parent.
But I keep getting the good old 'Object reference not set' error and I can't figure out why it's not finding the parent of my object.
The debug reports correctly, but it craps out when doing the assigning (ie, doesn't know what 'doorChecker.transform.parent.gameObject' is
Debug.Log("Number of Door Checkers = " + doorCheckers.Length);
foreach (GameObject doorChecker in doorCheckers)
{
GameObject doorRootObject = doorChecker.transform.parent.gameObject;
Highlighted object in the hierarchy is what is assigned to 'doorChecker'
You mean doorChecker.transform.parent.gameObject is null or the property somehow doesn't exists according to the compiler?

I personally when doing statemachine, it's easier to do it polymorphically.
a what now? xD
At a guess, you have a doorChecker in your array that does not have a parent
or you have null entries in the array
It relies on something called abstraction.
public abstract class BaseState
{
public abstract void MethodToUpdate();
}
public class StateOne : BaseState
{
public override void MethodToUpdate() { }
}
public class StateTwo : BaseState
{
public override void MethodToUpdate() { }
}
These types can be considered BaseState and when you try to call their MethodToUpdate it depends on the actual type of the object.
If the value is a StateOne, it calls the MethodToUpdate from that. And so on.
public sealed class StateManager
{
private BaseState base_state;
public void CallTheUpdate() => base_state.MethodToUpdate();
public void ChangeState(BaseState new_state)
{
base_state = new_state;
}
}
And then you would traditionally have some state manager that all states need to hold, just put it in the constructor of the BaseState so all classes that inherit it(see the : part then the BaseState, the type will hold everything the BaseState has) will automatically have it.
This way, each state object represents a state of it. Better than chaining tons of if or switch cases.
If you still can't understand this, i'd suggest you to watch a video about polymorphism or abstract.
And you totally should imo, you don't just pick-up new concepts and expect to somehow perfect it. 
This is so weird. I removed that line temporarily and added debugs/object renaming....
foreach (GameObject doorChecker in doorCheckers)
{
Debug.Log("I am a door checker");
doorChecker.name = "ThisIsWhoseParentImTryingToFindAndMyParentIs";
This works fine, but as soon as I add the line to find the objects parent, it craps out (even adding it to the end of the rename (hence the 'And my parent is).
why do you not just debug the data, then you would know. what you have done is pointless because you know no more now than you did
Not sure what you mean, sorry.
if (doorChecker.transform.parent == null) Debug.Log(doorChecker.name + " has no parent");
Ah okay, thank you.
how to make a game object when dragging know its on a ui and when release mouse it snap into said UI element
that is what you should have done as your very first step
huh, okay, so it's the addition of .gameObject to the end of the line. Which is weird, cause that is what everything I've seen/read says that's what to do. lol.
can someone help me idk how to make the player move (idk how to put a script like : if button pressed then move player up)
no it's not weird, if doorChecker has no parent then it can not have a parent.gameObject can it?
In the case transform.parent is null, trying to access gameObject on null will throw that exception. So your object has no parent
I'll give that a shot though I feel like this is way more complex than it needs to be for this scenario. I basically just want to have a list of idk 100 states each from seperate "state machines" but that state only holds info regarding a situation in the game like a single string or something (say like NorthWoodsGhostSeen -> NorthWoodsGhostFought -> NorthWoodsGhostSlain) .
but doorChecker does have a parent, which is what is confusing.
You have elements in your list that don't
you only think it does. Did you add the if check I made? What did it output?