#💻┃code-beginner
1 messages · Page 4 of 1
Please, read through #854851968446365696 "Asking Questions" section (at the very top) and ask your question again
What about all the people who were already helping you and gave you stuff to fix and then you just wandered off like a kid lost in a supermarket
Tutorial for begginer on discord where ?
look through pinned messages
and the unity !learn pages
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
Please, speak in complete sentences.
And post your current code in a pastebin link, such as https://gdl.space
Please, follow instructions, in order to receive help.
surely after 5 hours of repeating the exact same question, you'll eventually realize that you're not asking properly
I wish i had ur gaming maker skills
pls hrelp me
there is no voice here
no.
@oblique gazelle If you continue to spam the channel and ignore people helping you you'll be muted again.
I am trying, but you will not engage in actual conversation.
People get help here every day.
Most people have no idea what they are doing.
But they do get successful help, when they
- Properly answer questions
- Follow instructions
- Speak in complete sentences
What I did find, is a channel with a video, with what I think you are asking about:
https://www.youtube.com/watch?v=CxI2OBdhLno&ab_channel=RoyalSkies
Mouse control is one of the easiest ways to control looking around in a game. It also turns out to be very straight forward code. Learn the basics of Mouse Input in Unity over the next 2 minutes!
Movement Control Code Tutorial: https://www.youtube.com/watch?v=iu5hw8WFmmQ&list=PLZpDYt0cyiusT185fsSTEU1ecr8CcTYMP&index=9
If you enjoyed this video...
He makes short videos that get straight to the point.
Oh royal skies does unity content too? Cool. I know him from those blender quick tutorials
He did, before switching to Unreal.
pls join voice
No.
Dude, seriously. I wrote all that. Did you even read it?
just ignore him at this point
he is trolling
They're posting in between counter strike rounds and then immediately fucking off without reading any responses like farting in an elevator
!mute 266251267314155520 3d you've been muted before, and now you're muted again. This is your final warning, if all you want to do here is spam requests for help instead of listening to answers and learning, you will be banned next time it happens
ryldex was muted.
This is how I deduce what is going on in the other person's head.
By making instructions so clear, that their lack of response becomes reprehensible from any angle.
Unless there is some method to the madness
Anyway, that's over now.
Some people dont want help, but solution to all of their problems within one sentence
which is line 27
yes. your error is one line 27 of BossCutsceneAnim.cs
it is going to one script but referencing something in other
you should still read that link i sent so you can familiarize yourself with how to solve these issues yourself in the future
the error is because it isnt finding the reference to something
I have managed it manny times
I was just finding it weird
but I saw the problem after u said line 27
yes and the link i sent shows you how to read the error so you can see where it is occurring
also do u have any idea why the custom crosshair is so big in the web build but way smaller in downloadable
this is a code channel
yah I checked it thank you
oop ur right
https://hastebin.com/share/udinijakiz.csharp hey friends, i've tried to set a max zoom in/max zoom out float on a dynamic zooming camera for a 2d platformer... but its not working. if i hold down the space bar it can zoom out indefinitely.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
not without seeing your code
it's not clear from the video what is causing it. but if you think it is a code issue, then share the relevant code
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
oh also, is there a reason the player is a child of the tilemap? 🤔
and in fact has a Tilemap component and tilemap renderer component :O
oh wow yeah, this is all kinds of weird
I mean what I said ¯_(ツ)_/¯
Hard to say. There are several things wrong
probably start over
don't use Tilemaps as characters
share your code as per the bot message above
then try again
If you're following a tutorial I'd say start from the beginning
i'm gonna bet that the player tilemap has a few other tiles on it and maybe even a tilemap collider which is causing the rigidbody2d to make it freak out. and then the transform.Translate in the code is probably making it worse
thank you - yes mixing transform.Translate with Rigidbody motion is definitely a bad idea
but it's only one of your problems
when using a rigidbody you should stick to the rigidbody for movement rather than moving it via the transform. that way you won't be ignoring colliders when moving and actually moving with physics.
there are a few ways to move a rigidbody, you can assign its velocity, you can use AddForce, or you can use MovePosition. the latter is intended to be used with kinematic rigidbodies though
im having trouble with the camera, whenever i turn, its choppy
stuttery camera rotation usually means you are multiplying your mouse input by deltaTime
i dont think i am
mouseY = Input.GetAxisRaw("Mouse Y");
yRotation += mouseX * sensX * multiplier;
xRotation -= mouseY * sensY * multiplier;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
camHolder.transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
orientation.transform.rotation = Quaternion.Euler(0, yRotation, 0);
transform.rotation = Quaternion.Euler(0, yRotation, 0);```
why do you have both a sensitivity and a multiplier? 🤔 the sensitivity is the multiplier
but it's also possible that you are simply moving/rotating the camera on a different time step than your other objects. or perhaps doing it earlier in the frame.
my advice is to just use cinemachine. it's super easy to set up for a basic camera like this
cinemachine?
idk what that is
but uh
this wasnt a problem before
this became a problem after i tried to add networking
and i've since then given up on the networking and reverted the scripts
i only changed 2 of them and looking through them, i cant seem to find anything that could be the issue
i've looked at cinemachine now but i would rather fix the problem with my camera
perhaps its some setting in the editor i need to change?
then provide more context
should i show the hierarchy and the inspector?
sure. also more of the code
your sensitivity is about 100x higher than it should be
the camera has a follow script
the multiplier is 0.01
cuz 100 is an easier number for me
makes more sense to me at least
the camera follow script is just private void Update() => transform.position = cameraPosition.position;
lol i tought i have some crazy fps my monitor cant render so i turned vsync on and the stutter gone. or maybe its a editor hiccup
100 * .01 is easier than setting it to 1?
so not only are you potentially updating its position earlier in the frame than your objects move (which can cause stutter), but you're probably rotating it earlier in the frame too
no i mean its easier if i wanna change the sensitivity
how is that any easier
cuz then i can change it to something like 120 rather than 1.2
and i like whole numbers
so what should i do, move all camera stuff in fixedupdate?
depends, do you move your other objects in FixedUpdate? if yes, then yes moving the camera at the same rate you move your other objects is ideal. if not, then try LateUpdate so your camera isn't potentially updating 1 frame late
i move the player in fixed update
do i need to change the scripts in any way or can i just turn the Update into FixedUpdate
okay well i'm going to go back to my earlier advice and say just use cinemachine
if you want to fix this then read this article and good luck: https://kinematicsoup.com/news/2016/8/9/rrypp5tkubynjwxhxjzd42s3o034o8
alright thanks
hey I already posted this but just gonna try again.
This is suppose to generate a line between the startpoistion and end position.
the line doesn't appear.
Ive checked the camera, layers, line width etc,
made sure the points are in the right place
but it still won't display the line
I made sure the function was running with debug.
Is the line renderer set to display in world space
can u screenshot the inspector with the object that has linetest on it? just curious if theres any errors or if all the fields have something assigned to it
if you manually type in the values for the line renderer in editor, does it show?
Try logging startPosition.position and endPosition.position and see if they're where you expect them to be
whats in the gameobject transform doesn't match up with what displayed in debug.log
hold on
why would they be so different
Are you referencing prefabs? Do the objects have parents?
they are children of the player object so they move with the player object
Is the parent scaled?
can you screenshot line componeont
I made the ball smaller recently.. but before I made the gameobject
so I guess it is scaledi think
If so, you can follow along without scaling the objects using parent constraint component https://docs.unity3d.com/Manual/class-ParentConstraint.html
inspector is local pos , and youu're printing world pos
The inspector shows local position, relative to the parent. You're printing the world position.
does anyone understand why I am getting extra y axis rotation when im not facing the default world axis? transform.DORotateQuaternion(slopeInfo.transform.rotation * Quaternion.Euler(0, transform.eulerAngles.y, 0), 0.1f);For reference the transform is my character and slopeInfo is the slope im on
ok I set up the parent constraints the issue was the same but I am glad I know about this now
I had no problem with creating a line renderer from a drag motion so odd
If anything consider printing the local position and seeing if it's the value you want. I'm not able to see the behavioral changes since I'm not in front of your computer. See if the values are accurate and go from there.
the position from the debug.. how can I see if they are the same as the ones in the inspector if inspector is world view?
The inspector values are the local position
they are now the same
still nothing
also just tried a new shader for sprite diffuse, and default sprite shader nothin
hey i have this issue in my 2D platformer controller where on my tileset, the sloped terrain will have the 'player' slowly slide down without moving and is overall not pleasant to the eye or feel, here is the code: https://hatebin.com/gdmpuqgzfk, i'm hoping there is a simple fix to this because i've seen this in games and it looks really well made and i want to know how to do that properly
I have a puzzle i'm trying to create that consists of 4 arrows with different rotations, that require the player to interact with each arrow in the right order. How could i go by doing this, while also allowing for me, to be able to customize the order of buttons from the editor?
well i would say you could use if statements on variables that define the order through the editor, and if the if statements do match up at any point than reset back to the first
but i'm not entirely the most educated
okay
as long as you know basic c# than you should be generally alright, however if you need help with the code i can give you a example
Nah i think i got it, thank you.
yeah no problem
Queue and serializable class
I got it working, suprisingly on my first try, i just used a list of directions, and checked if the current button, contains the name of the first direction, and if it does it increases the current index in the list, and if not it restarts the index to the beginning.
thats actually pretty smart, nice job
i think my issue might have to do with how i setup the controller, its mainly based on a rigidbody
a betatester showed me this and I don't know how to fix the error of the enemy that keeps on repeatedly flipping up
time to add some logging
for me it's seems to be working, I barely see this
can you clarify for when it should flip in your logic
Is there a way to save a scriptableObject? I want to be able to have a question and answer as input........ and later be retrieved(even after closing the game).
yea look up save/load json
I always see them working, I don't know
here is the code
well, according to your video there it's not working ^^
if ((_enemyMovement > 0 && _isFlipped) || (_enemyMovement < 0 && !_isFlipped))
{
FlipModel();
}```
Could you explain your logic here
that raycast looks a lil short tho if its never grounded it will keep flipping
Ah, ok I think I understand it. If you're getting help from your teacher you should ask them to leave comments, but what I believe is the idea is that it should flip when it comes to a ledge, but since your enemy is too far above and the raycast is too short like BlinDeex was saying, then it's going to be stuck flipping.
well..... it's hard to explain it, I don't know how to explain it
You can try to refactor to be more discrete, I.e.
if (enemyMovement > 0)
{
SetLookRight();
}
else if (enemyMovement < 0)
{
SetLookLeft();
}
(Or some enum for left/right)
This should prevent weird logic states
Yeah that's more preferable. You can have the !is_looking_right condition inside the LookRight function instead.
That was my first thought, but the origin is an offset transform. That doesn't mean it's the right transform or it's in the right place though.
For anyone that knows game maker, is it possible to do procedural animation with gml visual?
maybe someone knows opel astra 2008 how do I do clutch replacement
In web development there is a thing called a “from” where you fill out some questions and then you submit the form… is there an equivalent for C#/Unity?
hey i know i should be patient but i wanted to check in about this
I don't know, no. You can use Tile map for the world.. not sure why you'd want it for the character
would this be a better issue for #🖼️┃2d-tools ?
Is there a way to search for all objects with a script attached to them, regardless of script name?
Whether i be searching through a prefab or a scene. Am using either of the search windows in the images featured
use t: InsertScriptNameHere in the search bar . . .
I want to find all objects with scripts attached to them regardless of script name
if I did t:MyScript it would only find objects with MyScript.cs attached
that's not actually useful rn
You mean ANY script attached?
huh? you ask for all objects with a script attached to them . . .
ya
exactly, your method would only produce the objects with the script of the same name
you'd need a base class to search for . . .
what are you trying to do?
I tried t: .cs but it doesnt work
that's not a script name, that's a file extension . . .
That is a file extension not a base class
what is a base class
again, what are you trying to do?
so do I search for MonoSingleton
every script attached to a GameObject derives from MonoBehaviour, just use that . . .
#include <stdio.h>
void print_time(unsigned long stamp) {
int seconds = 0;
int milliseconds = 0;
int microseconds = 0;
auto cps = 1000000; // mps_clocks_per_sec();
unsigned long s = stamp;
if (cps >= 1000000) {
// cps is microsecond resolution
if (s >= 1000000) {
// stamp exceeds 1000000 microseconds (1000 milliseconds)
seconds = stamp / 1000000;
milliseconds = stamp - (seconds * 1000000);
// stamp_ms must exceed 1000 microseconds
unsigned long stamp_ms = milliseconds;
milliseconds = stamp_ms / 1000;
microseconds = stamp_ms - (milliseconds * 1000);
} else if (s >= 1000) {
// stamp exceeds 1000 microseconds
milliseconds = stamp / 1000;
microseconds = stamp - (milliseconds * 1000);
} else {
// stamp does not exceed 1000 microseconds
microseconds = stamp;
}
} else if (cps >= 1000) {
// cps is millisecond resolution, do not convert to microseconds
if (s >= 1000) {
// stamp exceeds 1000 milliseconds
seconds = stamp / 1000;
milliseconds = stamp - (seconds * 1000);
} else {
// stamp does not exceed 1000 milliseconds
milliseconds = stamp;
}
} else {
// cps is in seconds resolution, do not convert to milliseconds
seconds = stamp;
}
printf("Clock: %lu\n", s);
printf("Clock seconds: %d\n", seconds);
printf("Clock milliseconds: %d\n", milliseconds);
printf("Clock microseconds: %d\n", microseconds);
}
int main() {
print_time(3118490); // 3 seconds, 118 milliseconds, 490 microseconds
printf("c = %d\n", 3118490);
printf("cps = %d\n", 1000000);
printf("c/cps = %d\n", 3118490/1000000);
return 0;
}
Anyone know what's wrong?
This doesn't look like Unity code
are we s'pose to guess what this even is, what you're trying to do, and what is not happening compared to what should happen? also, what digiholic mentioned as well . . .
Hey I have a little issue with a 2D platformer where when I make a moving platform the player does not always move smoothly with it. With a vertical one it send the player up a little above the platform when it reaches the top and starts going down. Also with horizontal ones the player moves with the platform but slides a little when it switches directions. I'm using rigidbody.velocity for player movement and platform movement. The way the platform moves is by setting a counter to count up and down depending on which way the block is moving and it'll flip and start moving the other way once the counter goes up or down. That part works fine but how do I get the player to stop sliding on the platform without using a crazy amount of friction because then the player struggles to move on the platform? Also with the vertical moving block how do I get it to not send the player into a little jump at the top?
could i please get a follow up on this?
In a string can I modify the color of specific characters?
wdym string color?
I'm trying to create a JSON by parsing multiple objects in a foreach loop, now, the way I'm doing it is by building a string and then converting it into JSON.
void Saver()
{
Asset data = new Asset();
Debug.Log("Saving file as level_" + levelName + "...");
var sb = new StringBuilder();
assetScript[] scriptobjects = Object.FindObjectsOfType<assetScript>();
List<GameObject> objects = new List<GameObject>();
foreach (assetScript script in scriptobjects)
{
objects.Add(script.gameObject);
}
foreach (GameObject obj in objects)
{
data.objName = obj.name;
data.posX = obj.transform.position.x;
data.posY = obj.transform.position.y;
data.assetId = obj.GetComponent<assetScript>().assetId;
string json = JsonUtility.ToJson(data, true);
Debug.Log(json.ToString());
sb.AppendLine(json);
}
File.WriteAllText(Application.persistentDataPath + $"/level_{levelName}.json", sb.ToString());
}```
This is fine however I need these objects to be in an array for loading purposes, I tried making a list of objects but the output file is always {} and i don't get why.
this is the code with the list:
void Saver()
{
List<Asset> dataList = new List<Asset>();
assetScript[] scriptobjects = Object.FindObjectsOfType<assetScript>();
List<GameObject> objects = new List<GameObject>();
foreach (assetScript script in scriptobjects)
{
objects.Add(script.gameObject);
}
foreach (GameObject obj in objects)
{
Asset data = new Asset();
data.objName = obj.name;
data.posX = obj.transform.position.x;
data.posY = obj.transform.position.y;
data.assetId = obj.GetComponent<assetScript>().assetId;
dataList.Add(data);
}
string json = JsonUtility.ToJson(dataList.ToArray(), true);
Debug.Log(json);
File.WriteAllText(Application.persistentDataPath + $"/level_{levelName}.json", json);
}```
hello, how can I instantiate an array of gameobjects in a straight line with equal spacing with each other?
I want to use this for my game's status effect indicator. And is there a way for these game objects to align themselves when the first status expires like this:
X X X X - 4 status indicators
X X X - the first status in the left has expired
If these are UI elements, consider using the Horizontal Layout Group
https://docs.unity3d.com/Packages/com.unity.ugui@2.0/manual/script-HorizontalLayoutGroup.html
Hi. Is there any code that can keep my camera locked for lets say 5 seconds? I always start the game looking at the floor or wherever because i'm holding my mouse.
So the way I use this, is to instantiate the statusEffectGameObjects in the gameobject where the horizontallayout is attached as their parent?
yep and they should just sort themselves based on the values in the inspector
alright thank you
deleting or disabling one of the children should also cause it to reorder
so you should get that "shift over" behaviou you wanted
i want to make some paper just visible in specify zone. i start use sprite mask but i already use sprite mask for paper. Is there have another way i can do ?
I want my camera to stay stationary for 3 seconds when the game starts. I've tried this void start and many other things. it doesnt work, any help?
if(Time.time < 3) {
return;
}
at the start of the method
also don't multiply mouse input by deltatime
Where would this code go?
fml I've mad eit so my mouse deactivates after 3 seconds xD
You are a saviour. I had a dumb moment. spent hours on this. it works flawlessly. Thank you so much. Also you mentioned not to multiply mouse input by deltatime. How comes?
Hi. In the tutorial to get my unity project unto github they use a new file and can easily match the folder directions. However im using an existing project, and i cant seem to change the folder for this project to match the github folder.
I tried save as inside github doesnt work (doesnt allow a save)
I tried manually dragging the project files into github didnt work
hello
you just create the repository inside your project folder
Thank you.
Sorry to bother you again. I have my main menu scene as index 0 and my first level as index 1. the 3 second timer starts while I'm on the menu. So if im on the menu for 4 seconds. the timer has already passed. I didnt know that the other scenes are active. Do you know a way top deactivate a scene until it's active?
i drag gitignore into the project file, but github doesnt react. Bullshit system i give up
just create the repo right inside the project folder
or drag all of the files created by git in whatever folder you created the repo in into your project folder. then you can point your gui client (probably github desktop if i had to guess) to that folder
it's not a "bullshit system" just because you don't know how to follow directions
Does anybody know why this setup introduces a delay when moving from "Midair" to "Idle"?
But when using this setup there is no such delay?
sry
I'm a little confused about this Graph class. It says its type is Location but you can use it with whatever other type? What is this called? I've been trying to google what this is but I can't really find anything. Type override? I had assumed you needed to make it generic to do something like this. The <Location> is declaring which type can be overriden I guess?
I'm pretty sure this is just a generic class where the generic type parameter is called Location. it's not actually using a type called Location here, it's just the name you've given to the generic type parameter
replace all instances of the word Location in that class with T and it will make more sense to you as to what is actually happening
Yeah as T it makes more sense to me but there's also a struct for Location so idk
I guess it still works that way
right but that struct is 100% irrelevant to your Graph class. you just happened to give the generic type parameter the same name as the struct
the reason i suggested replacing Location with T in Graph was because it is functionally the same exact thing. there is no difference except in the name of your generic type parameter. T is just the standard name used for it much like how i is the standard loop iterator name. you can give it whatever name you want, in this case you've given it the name Location, and it doesn't change what it is or what it does, just what it is called
for(int i = 0; i < 3; i++)
Debug.Log(i);
for(int Location = 0; Location < 3; Location++)
Debug.Log(Location);
these loops are functionally identical. the only difference is that i called the second loop's variable Location instead of i. that doesn't mean it has anything to do with your Location struct
Yeah I guess.
Hello I was trying to build my game but this error message kept apearing
you can't use the UnityEditor namespace in a build
how do you fix that
editor code should be wrapped in conditional compile directives or be put into a folder called Editor
Im not really sure what that means
why are you even accessing the Build class namespace in a PlayerMovement script? 🤔
hello, I have 2 Transform object. I wanted to set one object's rotation.y so that the first transform is facing another transform.
How do I do that?
What I'm doing now is
deltaTransform = transform1.position-transform2.position
and then setting the rotation like this
transform1.rotation.y = Mathf.atan2(deltaPosition.z,deltaPositionx)
transform1.rotation = Vector3(0f,Mathf.atan2(deltaPosition.z,deltaPositionx),0f)
is this incorrect? it doesn't seem to do what I wanted.
I really dont know
so remove it
well to start off that second line is a compile error
thank you so much boxfriend
ah yes. its error.
uhhmmm let's pretend that it's not and it actually change the Transform.rotation.y, what else would be the problem?
did I miss some magical function or maybe I'm using wrong measurement, like degree and radian.
well Atan2 does return the angle in radians. but you don't even need to use it. just use Quaternion.LookRotation to get the desired rotation
what the fuck is a quaternion, apologize for my language.
here's an example of how you can do that since i guess you don't know how to use google: https://discussions.unity.com/t/making-an-object-rotate-to-face-another-object/27560/3
You should cut editor related content out of your non-editor related code
Unity has a lot of build in inheritable classes that make it easier to do this
Generally your editor code ends up in a seperate file inside an Editor folder. Unity will automatically strip these files when you make a build.
Otherwise, use conditional compilation as boxfriend mentioned, which means Unity will ignore the editor specific code inside the conditional
It's just a variable that contains a rotation.
That's all that matters
Hello, I'm very new to programming. And I was wondering if there was an Unity in-build way to verify that someone has drew correctly on a pre-set segment ? Maybe, a kind of trigger or whatever ? I don't even know how to put my question, sorry if I'm being confusing.
Like in those learning app where u have to draw a symbol ans it checks if you have written it correctly. Thanks you
Like verifying that each segment has been drew on the right place ? Some kind of trigger that i'm not aware of maybe ?
The asset store ? Sorry i'm very new (and dumb btw)
Where people make custom tools, assets, etc. See if someone made a game template or something that includes this feature.
Yes, the asset store
Yes, you can google the Unity asset store for the link
The thing is I don't even know how to formulate my question ahah
In a simple and programming-like sentence yk
Symbol recognition
Glyph recognition
Handwriting to text
Stuff like that
Kk tks yall
Was gonna say scribble detection but that sounds more accurate^
Anyone here know how to get a 2d sprite to point at the mouse? Because I tried but I kept pointing in 3d and disappearing.
get direction from sprite to mouse, assign either its transform.up or transform.right to that direction depending on the direction the sprite faces when not rotated
don't use transform.LookAt for 2d objects
So I just use transform rotation and set it to the direction of the mouse?
no, did you even read what i said?
Yeah, get the direction of the mouse from the sprite and use transform to set the rotation of the sprite to that of the direction of the mouse.
please learn to read
You said to get the direction and assign it as a transform
Isent that just (0,1,0)
transform.up is the direction of the objects' Y axis. when the object is not rotated at all then yes it will be 0,1,0
How do you get a sprites position again?
you get the position from its transform
How can i make a custom SpawnPoint
using UnityEngine;
public class ObstSpawner : MonoBehaviour
{
public GameObject ObstPrefab;
public float SpawnSchnelligkeit;
private void Start()
{
InvokeRepeating("SpawnObst", 0f, SpawnSchnelligkeit);
}
private void SpawnObst()
{
Instantiate(ObstPrefab, transform.position, Quaternion.identity);
}
}
?
like a object where it spawns
instead of the object whit the script
instead of using transform.position (which is this object's position) as the position to spawn it at, you can create an empty gameobject at the location you want it to spawn and use that object's transform.position. or you can just create a Vector3 variable and use that
thanks
Ok thank you I got it working
why when i added line 52 and function 'private void OnApplicationFocus(bool focus)' movement stoped working and character started to fly...
Your file doesn't have line numbers. Use a paste site: !code 👇
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
How do you make it so you stay in place and everything else moves?
Instead of adding code that makes one object move to the right, you add code that makes everything else move to the left
hey! I have a weird little bug where the projectiles don't get emitted properly
My assumption is that it break because I use time.DeltaTime and because framerate isn't constant, it sometimes leaves small errors like that
how could I make it, so it's not frame dependant?
Quick question: If i instantiate something as a child but the Parent has a 1.5 scale ratio how do i instantiate my object to keep its own 1 scale ratio?
Consider using the parent constraint component and not parenting.
im not sure what you mean by that
Parent constraint lets you move an object as if it were a child object without actually being one
Thanks!
Hey I'm trying to create a unity game but I honestly don't know how to start the game
....what do you mean?
Manual for the component: https://docs.unity3d.com/Manual/class-ParentConstraint.html
Script doc for the component: https://docs.unity3d.com/ScriptReference/Animations.ParentConstraint.html
(I cannot write code - I'm on mobile)
Play button on the top of the screen
Ok
anyone?
I was thinking perhaps making it depend on distance from a source point?
You mean the spacing is inconsistent for the purple particles?
yeah
and it's even more appearant when the projectile has a high speed and emission rate
Is it using emission over distance?
Ah. Well, you need to show the code that emits them
sure
public class SubEmitter : MonoBehaviour
{
[SerializeField] GameObject[] projectiles;
public float atkCoolDownCT;
[SerializeField] private float fireDelay;
private int currentProj = 0;
private float atkCoolDown;
private float stunTime;
private void OnEnable()
{
atkCoolDown = atkCoolDownCT + fireDelay;
}
void Update()
{
stunTime = EnemyStagger.StaggerInstance.stunDuration;
if (stunTime > 0f) atkCoolDown = atkCoolDownCT + fireDelay;
if (atkCoolDown <= 0f)
{
atkCoolDown = atkCoolDownCT;
FireProjectile(currentProj);
currentProj++;
}
else
atkCoolDown -= Time.deltaTime;
if (currentProj > projectiles.Length - 1) currentProj = 0;
}
private void FireProjectile(int index)
{
GameObject projectile;
projectile = ProjectilePools.ObjectPoolInstance.GetPooledObject(projectiles[index]);
ProjectileHandler projHandler = projectile.GetComponent<ProjectileHandler>();
if (projectile != null)
{
projectile.SetActive(true);
projectile.transform.position = this.transform.position;
projHandler.SetMoveDelay(GetComponent<ProjectileHandler>().LifeTime);
}
}
}```
its a pretty basic implementation
Maybe decrease from atkCooldown first, then check if it is 0 or below
I also have a list of projectiles instead of one so I can make it so it emits proj1, then proj2, etc
thats what (atkCoolDown <= 0f) does?
Yeah but im suggesting doing the atkCooldown -= deltatime first, them checking if it is <= 0
hmm
idk what that'd change
but I can try
oh yeah, I also do atkCoolDown -= Time.deltaTime inside of the else statement
Like with the code the only thing I have is the model
Currently you are using the atkCoolDown value of the last frame, not the current one
@verbal dome tbh for the time being I "fixed" the issue by increasing the projectile size, so its much less appearant if there are small issues
but ill try to see if what you said really fixed it
Its a guess
it didnt fix
there are still inconsistencies
I think the main issue has to be Time.deltaTime
but I'm not sure how to make the emission of the smaller projectiles not framerate based
You probably have to do some interpolation math to make them spawn on consistently spaced position instead of the current position
Im not great at explaining it
because in extreme examples, if there's 1 second between the current frame and the frame before, then it not only moves more because of the movement using deltaTime too, but also the emission
yeah, I get it
it kind of reminds me of the hit detection issue
where if a gameobject moves too fast, and the framerate isn't high enough, then it has the chance of completely missing collision with an object that was in it's path, because there wasnt a frame that captured the collision
so smth that people did is draw raycasts between where the object is, and where it was
and using that to detect collision
Seems like parent constraint component only have position/rotation. i found scale constraint component but if i freeze my scale still gonne scale according to parent.. idk what the deal with them.
i also tried :
GameObject go = Instantiate(...); go.transform.localScale = new Vector3 (1,1,1);
what id do personally maybe is instantiate the object and then set it to be the child of another
that's smart. easy & working.
so maybe it should be better to resize my model in Blender rather than set its scale in unity... for now i don't see the problem, i only use it for loots to spawn in containers. its a extra line of code and might gets on the performance on a larger scale but thats why loading screens there for 😄
hey guys sorry for the strange question but why can I not use Random.Range() while using System in my monobehaviour?
That problem is called "tunneling" in game dev btw
In Unity you can solve it by turning on continuous collision detection on your Rigidbody
Info here if you care https://docs.unity3d.com/Manual/ContinuousCollisionDetection.html
because both System and UnityEngine have a class called Random
to use the Unity one add
using Random = UnityEngine.Random;
thank you so much man appreciate it!
public void quit() => Application.Quit();
Hello, i made a button to quit my game but when i click on it nothing happen, any idea please ?
Application.Quit only works in a build
oh good to know thanks
yeah heard about it because I had it happen too
I made a raycast for interactables and now I'm wanting to use a second layer for triggers but struggling to have them together. plz help
So, if your raycast hits something in the mask layers, but that thing doesn't have the interactable component, you want to cast again, and see if there's anything in the layertrigger mask instead?
Yes. I think that would achieve the same thing. probably a better way to do it. I have a feeling my "else" part is the issue
No, that's what you're currently doing. I'm asking if that's what you're intending to do
If your first ray hits something, and that thing has no interactable, you cast a second ray with the same parameters
so I should get a message in my console right? My second one is for triggers. make things happen etc
What's the first ray hitting?
Anything with the "interactable" layer
Okay, so what object is it hitting when you're expecting the second ray to cast
a cube with the "LayerTrigger" layer
Does the mask layer mask contain LayerTrigger?
yes
Is there a way too comapc this in one app?
Right click -> Send to -> Compressed (Zipped) folder
So, is that layer in both mask and LayerTrigger masks then?
i mean like that only my game is displayed
as a icon
Are you talking about this?
Okay, so, what object in the Interactable layer are you expecting to hit, that will then cast a second ray to find something in the Collision layer?
do someone know how to get rid of this message in visual studio code?
Trust me you're going to want them
That's code lens, but why would you want to disable features that make it easier to debug and to understand how your code works and finding where things are used/not used
You've lost me. I won't lie. I have interactable (keys,batteries etc) they all work perfectly. I wanted to use Raycast to trigger colliders.
Again, what you are currently doing is checking if your ray hits anything in the Interactable layer.
If that raycast connects with something, you then check if it has the Interactable component.
If the object that it hits does not have that component, you then cast a second ray to find things in the Collision layer.
So I'm asking what is the object in the Interactable layer that doesn't have the Interactable component that you are looking for
What do it mean when the vscode file is "untracked" and is having a green glow
It has not been added to git yet
Thanks!
Can you remove those messages even tough it's not been added to the git or is modified?
@polar acorn I changed the position of my collision and it works. it registers me hitting the collision layer.
This is no longer checking for if the first ray hits anything before casting the second
Interactable interactable = hitInfo.collider.GetComponent<Interactable>();
This line right?
I noticed that and literally face palmed
also just use a TryGetComponent
Added to my notes to look at. Thank you.
Whats the cause of a lag spike when colliding with a trigger?
Use the profiler to find out
Add them to git ;)
On it now. So I'm just looking to see where my lag spike is and then trouble shoot it from there right?
Working on scripting an animation for my weapon in my game, but having issues with the animator rn. I have it setup so it has a basic
Turn Bool to True and start animation
When animation is done
Turn off bool and transition back into idle state
kind of script. I had the transitions setup properly and debugged to get the bool when starting the scene. Everything checked out right but the animation wouldn't start. I rewinded a bit and took it step by step and am now just trying to get the animation to play when the scene starts. However, even that isnt working
not sure whats wrong and why the animation wont just start playing as soon as the scene starts. I have the animator and animation properly setup on the weapon's object as well and have the firing animation as the default state for debugging.
how do i fix the curser being that weird square
press insert on your keyboard
thanks
im trying to display the y coordinates of an object (2D) but cant find anything online. does anyone know how to do this?
display it where
just on some random text in-game
whats the issue
i dont know how to do it
what part dont you know how to do
where are you getting stuck
what hve you done so far
i dont know how to track the object
use Debug.Log
just reference it
already tried it
Debug.Log(theObject.position.y);
im gonna try
Does anyone know how to make something like this
Like what
Like an intro when I enter the game
use video player component or animate in unity with Timeline
Ok
Hello! Im making a game where the user saves their name and level in an input text field, and their stats are displayed in the text for the user to see. currently when the app closes all of the data goes away. I want there to be multiple saves whenever a user hits the save character button. I made a character class, but unity confuses me. Do i make a prefab named character and put my script on it? Or do i just make an instance of the character object call it profileOne? How should i go about saving the players name and level from the text and then display it in the text when a button is clicked from a specific character game object?
You need to save it to a file. Using json is kinda standard.
Having it in a script alone won't save it
okay awesome! ill check the unity docs! 😄
There is some way to use SerializedObject too, but it doesn't work by default and I haven't done it
okay! Thank you for your guidance!! ill remember that if this doesnt go well for me!
I've a big block of JSON which I'm looking to convert into URL Params in order to pass it to a Apps Script / Google Sheet. Does anybody know if this is a good way to send several pages of dictionaries? Anybody know of a good way to convert JSON into URL Params?
probably better to send them in the actual HTTP payload rather than the URL if there are a lot of them
can't you just directly send the json blob as the HTTP body?
hey friends, i'd like to add a collectable item to my platformer that shrinks the players size. i'm guessing i should just concentrate on shrinking the Y scale of the transform? (as opposed to the Y size of the box collider2D). i've tried it with this but its not working
in what way is it not working?
hey boxfriend! its not changing the transform scale
bro, you can use,, transform.localscale
okay so where do you actually try to change the transform's scale? all you do in the code snippet is assign to some fields in this class
i think this is what i might be missing
I hope I helped, I'm very happy that with 1 month of studying I can already help people
ok that worked, thank you!
now i guess i need to work out some logarithmic formula so the transform doesnt go beyond a certain value so the character can never shrink into nothingness
why not just clamp the scale? at a certain point it won't really make much sense to actually reduce its size anymore
wouldnt a logarithmic formula do a similar thing?
collider issue probably, lets see the player inspector with collider selected in playmode
getting caught on the edges of tiles is a known issue with the 2d physics engine that unity uses (box2d). there are a couple of steps you can take to try and solve this:
- set the rigidbody's collision detection to continuous
- use a round bottom collider for your player instead of one with a flat bottom
- use a composite collider for the tilemap
not exactly, clamping it would be a hard limit
I bet 3 would also fix it with square collider, maybe with no friction material helps too
yeah composite collider is probably the most efficient fix since that would treat the entire tilemap collider as one big collider instead of individual tiles. and it works with flat bottomed colliders (at least in the limited testing i've done, i typically still use capsules or circles for my players)
Can I create/delete a script with code?
depends, for what purpose?
show your code where you set the parameters back to 0,0
^^^ doh
So simple.. Just figured since there wasn't input it would go back to zero.. but yeah, you are right
Thank you.
how would i go about adding a background that's actually behind everything
what is the nature of the background? A static image? Something else?
how do i detect if an the object with the script on it is being pressed? im trying to do OnMouseOver() but that seems to do nothing
just a static image yeah
OnMouseDown or IPointerDownHandler
been a while since i played around with unity so im definitely just being stupid
I'd use a Screen Space - Camera canvas with a plane distance of 1000 or so
and just put an Image component across the whole thing
what is this if (pressed == false) thing
whjy don't you just use OnMouseDown?
this is overcomplicated
the pressed thing is just so the button doesnt get pressed again until the end of the animation
@meager ermine ^good option. If you are using sprites, you can just go to the inspector of the background and go to the sprite renderer within and change the order in layer
use OnMouseDown
you can still do the timer thing
but you don't need the extra bool
could you explain what OnMouseDown does exactly so I could understand better
Always start by reading the docs https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html
@wintry quarry @valid finch thanks y'all that helped
How is Barbie doing?
i have but i still dont really get it, nothing happens when i click
and im pretty sure i used it just like the example on the documentation
idk tbh i havent seen her in a while
This was my question before, but im not sure if you can save data to a json file building to android? Does the file system work on mobile devices?
get rid of the pressed bool entirely
and the if statement
put a Debug.Log statement at the beiginning of OnMouseDown
before any conditions
just start with making sure that works on its own
didnt get rid of the bool yet but put the debug before it right after OnMouseDown just like you said and it isnt saying anything in console
Does the object have a collider
no, is that why?
then you haven't set it up correctly. You need a collider for one.\
I guess you didn't read the docs I sent
i did but i skipped the collider part 😭
like 80% of the sentences on that page mention colliders 🤔
okay i pretty much just read the code part lol
added a collider and it works like a charm
why isnt the bool needed though?
the idea is to prevent the player from clicking the button again until the animation plays out
Actually the if (Input.GetKeyDown(KeyCode.Mouse0) is not needed
why's that there
we're already in OnMouseDown
yeah that was there before my bad
pressed is just a poorly named variable
it's not about whether it's pressed
it's about whether the timer is up
pressed makes sense to me though, since the animation is of the button being pressed
clickDelay
this is what I ended with and it works perfectly now
Your animator OnGround is not properly configured
That wasn't for you, I was just chiming in on a variable name
huh ? sometimes you're mid-air and OnGround is checked
you should show your setup on how you also call jump
How do you set Animator OnGround
show code
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
put this in your code
private void OnDrawGizmos()
{
Gizmos.DrawSphere(groundCheck.position, groundCheckRadius);
}```
hit play, make sure Gizmos is on in Gameview/scenecview
it says Gizmo on the Game view, to the right
hit play and screenshot game
so you didn't enable it..
click it
so it turns light gray
if you dont see a gizmo after enabled then your Groundcheck is nowhere on sight
where is your Groundcheck transform
nvm that
look at your groundcheck
that white sphere
Physics2D.OverlapCircle
thats how big it is
when its true
quite a bit
the variable you have for it
groundCheckRadius
put ground check a bit closer to your knee height
so it almost lines up to your collider bottom half
make it about same radius as ur collider but slightly bigger
Hey, if you are ***constantly ***changing a players gravity, with Rigidbody2d.gravityScale, does it matter if it is in Update() or FixedUpdate()?
like his leg height lol i said knee, that aint his knee and reduce radius
what does it need to be constantly ? you only do it once in a method
dont worry about animation rn
worry about fixing your huge groundcheck for code
something like this
maybe slightly more down but you get the idea now
animation wise you would still need to make the Transition timing smaller so you dont have 2 clips repeating
but it should fix your jumping / animation timing and wont be able to jump midair
you really don't see why?
what have we been doing this whole time..
you're checking for grounded bool to jump , are you with me so far?
the size of that check is as big as that big gray sphere yes?
as long as the gray is touching a collider Grounded in layer
is Grounded
and you can jump
Compare yours to navs
#💻┃code-beginner message
Look closely at how far the gray circle goes below where the green circle would be

thats still too big
you wil be grounded if your sides are touching a platform with Grounded layer
youd be able to jump even if your head is touching that platform
print("hit something");
if (hitObject.gameObject.tag == "Deleter" ) {
print("hit " + hitObject);
Destroy(gameObject);
}
}```
am I doing something wrong here, my walls have the deleter class.
do you really not see the differences
#💻┃code-beginner message
Why do you still have it so huge?
time for some glasses
The circle is bigger. That is the difference.
A LOT bigger. Your circle is taller than your character!!
time for a thicker pair
YOU set the size and made the variable
is hit something printing ?
also do you mean Deleter Tag ? not class
in the inspector of the script?
hit isn't printing and the tag is called, "deleter."
that is a trigger
you're using wrong method
oh
wdym atleast 1
close but still toobig and too far down
between the two collision/trigger one needs a rigidbody
bruh..
are you fr?
It has to extend past the green circle
The green circle is the collider, and it won't move down further than that
It's giving me an error saying,
"Script error: OnTriggerEnter2D
This message parameter has to be of type: Collider2D
The message will be ignored."
Make the parameter Collider2D then 🤷♂️
That IS what it's supposed to be
ehh ill take that
Sure, that is good enough probably
id still lift it up a bit but fine
did you fix the transition / repeating animation issue?
Is there a way to make it so a collider wont interact with another specific collider (like wont move it around or anything)
Layer based collision being that since object x isn't on the same layer as y it can't interract?
yes can be done in code for temporary or more permanent via Project Settings
https://docs.unity3d.com/Manual/LayerBasedCollision.html
they all interact by default ofc
for 2D this is under Physics2D category
I did it, thanks
Hello, I have some code setup to tell me the position of an arrow when the player is able to hit it and where the location on the x position it is when the button is pressed. For some reason in the unity editor the position on the arrow looks correct but the Debug.Log statement is kind of off and it triggers the "ok hit" instead of the "perfect hit" code when it's in the perfect zone.
I have no idea why it's doing this.
{
if (canBePressed)
{
if (Mathf.Abs(transform.position.x) > -1064)
{
Debug.Log("ok hit");
Debug.Log("ok " + Mathf.Abs(transform.position.x));
}
else if (Mathf.Abs(transform.position.x) < -1124)
{
Debug.Log("ok hit");
Debug.Log("ok " + Mathf.Abs(transform.position.x));
}
else
{
Debug.Log("perfect hit");
Debug.Log("perfect " + Mathf.Abs(transform.position.x));
}
}
}
}```
you're working with rect transform
use anchoredposition
Probably dumb question, but how do I access the index of a list that is inside a 2 for loop?
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
Vector3Int position = new Vector3Int(x, y);
float islandValue = heightMap[x,y] - squareFalloff[x,y];
if (islandValue < 0.4f)
{
tilemap.SetTile(position, water);
waterTiles.Add(tilemap.GetTile<WaterTile>(position))
}```
I want to get the tile that I just added into the list. I could use `tilemap.GetTile` again, but I'll have to access the list anyway later on also in a double loop.
So, if waterTiles is a flat list, it ends up being x * height + y to get an individual element at x,y
ty, i'll try it out
thank you, that worked 👍
Actually, I think that won't work out. I'll just use GetTile.
This is because of the if. When I skip to add into the list, then the index would jump in the other iteration. It would skip the current tile.
Until eventually going out of bounds
Ah, right, it's not a guaranteed add. Yeah there's no way to get the index in the flat list from the X,Y pair. Unless you build up a mapping yourself as you go
Do I need to explicitly call RefreshTile or is it already called by the engine when I use SetTile?
i have a 3d top down game that plays kind of like 2d 1942, i have WASD movement set up to move the character around without rotating it at all, i want the rotation to be based on where the mouse cursor is. how can i accomplish that? what ive tried so far looks janky and way off. im only looking to rotate the players Z axis and point where the mouse is
float camToPlayerDist = Vector3.Distance(transform.position, Camera.main.transform.position);
Vector2 mouseWorldPosition = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, camToPlayerDist));
Vector2 direction = mouseWorldPosition - (Vector2)transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0, 0, angle-90);
this kinda works but looks a little off
Maybe raycast to the floor and acquire the hit point. Offset the height to your characters eye position level then rotate towards https://docs.unity3d.com/ScriptReference/Vector3.RotateTowards.html
ill try that solution, thanks
Else if you need the character to immediately turn just assign forward to the direction.
I want have an input field for a question and answer. Then I want to save it as a scriptableObject.
I want to be able to close the application and reopen it and have the questions and answer show up.
Like a “test yourself study guide” game
So, I'm tyring to get the neighbours of a tile, but I'm getting an out of bounds exception. Anyone knows what is wrong with my array?
https://pastebin.com/QLSR5A40
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
You don't need to generate code for that
You just need to serialize the strings and save them to disk
Json?
I can only think that it is trying to get a tile that doesn't exists yet, but this shouldn't be a problem, because I made sure to return this if out of bounds of the tilemap
I have a problem with my player controller where when i press "R" to roll, the animation is delayed a bit
it only happens sometimes, and a example of it is at 0:02
does anyone have a solution?
*i can show you the animation controller for the player and the rest of the script
https://pastebin.com/mz6CfEke
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
does anyone know how to get the position of a item when the script isent attached to it?
use a tag
or make a direct reference to transform
how do i do that?
[SerializeField] private Transform myItem
Debug.Log(myItem.position);
so does that create a variable containing the position?
oh ok
ill try it out in a bit
is there a Resources.Load thingy for editor that can search anything in project folders even not in a Resources folder?
For what purpose
Ray cameraRay = cam.ScreenPointToRay(Input.mousePosition);
Plane ground = new Plane(Vector3.up, Vector3.zero);
float rayLength;
if (ground.Raycast(cameraRay, out rayLength))
{
Vector3 pointToLook = cameraRay.GetPoint(rayLength);
Debug.DrawLine(cameraRay.origin, pointToLook, Color.blue);
partToRotate.LookAt(new Vector3(pointToLook.x, transform.position.y, pointToLook.z));
}
what do i need to add/change here so that the part to rotate looks straight ahead and only rotates on one axis? right now it's looking at the floor which i dont want. the X in the image is about where i have my mouse cursor
is more what im going for
Anyone know how i could apply inertia to a 2d sprite without using rigid body components?
I have a ship that takes horizontal and vertical input but i need it to slowly come to a stop once the user lets go of one of those input
https://pastebin.com/gvVQ5WkH
why is it only dashing right :<
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
You can apply a deceleration to the movement speed that changes from its current speed to 0 over time . . .
cuz ur dashPower is always same atleast in that script
what do i do then?
https://www.youtube.com/watch?v=2kFGmuPHiA0
i followed this tutorial, just modified smths to my code
Learn how to add dashing to your game in Unity!
Source code: https://gist.github.com/bendux/aa8f588b5123d75f07ca8e69388f40d9
SOCIAL
Discord: https://discord.gg/5anyX69wwu
itch.io: https://bendux.itch.io/
Twitter: https://twitter.com/bendux_studios
SUPPORT
Buy Me a Coffee: https://www.buymeacoffee.com/bendux
MUSIC
The Thought of You by ...
idk the context when u want to dash left u could invert dashPower
uhh, sorry for asking again, but, how?
ig i do that with the sprite for left and right
i could try for dashing
https://gist.github.com/bendux/aa8f588b5123d75f07ca8e69388f40d9
in the original videos code, he has a code for flipping, how do i adapt one to my code without messing too much up?
you could just set the Y component of the point you hit
probably to the Y position of the robot's head
neat lemme try
you have transform.position.y there, but is that the right transform?
if it's the robot's transform, that's probably between its feet
partToRotate's y position may or may not be appropriate
also, why isnt Drop showing up?
idk but if I had to guess replacing part where u set velocity with this rb.velocity = new Vector2(Mathf.Sign(horizontalInput) * dashingPower, 0f); would fix it
thx
Nvm it showed up for sum reason
You may not have had saved the file, or Unity may not have recompiled yet
It won't recompile if you have any errors.
yoo
ty so much
it is working now
hey so im trying to hit the slime (which has a collider2d attached) which does hit, but if I stay in the same place and try to hit again it doesn't go through and if I move back outside the slime collider and go back in then it registers the hit. how can I make it that the hit will register in the same place without having to move back?
Here is the sword animation hitbox
Ah, so you're just colliding with them
then here is the sword hitbox true or false depending on when the player hits the key
I believe OnTriggerEnter won't be called again until the colldiers that collided have been disjoined
ah ok is there a different method i should be using?
You have this, but youll want to set up a timer/cooldown so you won't call every frame
Well, it will be called regardless, but you'll want to limit the logic contained else you'll instant kill your enemies ;)
alright thanks, is it defaulted to call on every frame?
I think it's based on fixedupdate? You can also just cast yourself using overlapsphere/overlapcircle and gauge the logic in an update loop
okay thanks for the help
Ye np
I'm in need of a hand if possible please.
I started using the Inventory system by Devion Games last year.
Took a break from Unity. It used to work but for some reason one button doesn't seem to function within the Unity UI now.
Every time I click it I get this error. Is a package missing that's clashing with the old code?
NullReferenceException: Object reference not set to an instance of an object DevionGames.InventorySystem.VisibleItemsEditor.ShowWindow (System.String title, UnityEditor.SerializedProperty elements) (at Assets/Devion Games/Inventory System/Scripts/Editor/VisibleItemsEditor.cs:34) DevionGames.InventorySystem.EquipmentHandlerInspector.OnInspectorGUI () (at Assets/Devion Games/Inventory System/Scripts/Editor/Inspectors/EquipmentHandlerInspector.cs:92) UnityEditor.UIElements.InspectorElement+<>c__DisplayClass59_0.<CreateIMGUIInspectorFromEditor>b__0 () (at <66e151436a4945b595f4b482260aa84d>:0) UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)
Basically the inventory system by Devion games scripts interfaces into Unity for ease of access references things in your database
Usually I'd click either button and get a pop-out.
Unfortunately the developer hasnt been active in a long time.
Hey, is anyone familiar with Physics Raycaster component? I have no idea what that is and I couldn't find anything in the Unity's documentation
But that doesn't say much, nothing else here
Okay, more or less I get it, thanks!
Is the code outdated then or they removed the Event functionality for the previous code?
What are you talking about, and why did you DM me? I was very clearly talking to the person directly above my comment
You have something null at VisibleItemsEditor.cs:34
it's unrelated to UGUI events
Ok thank you, apologies for DMing.
Thank you again btw, I realised it was as simple as spelling mistakes.
Vector3 pointToLook = cameraRay.GetPoint(rayLength);
pointToLook.y = partToRotate.position.y;
partToRotate.LookAt(new Vector3(pointToLook.x, pointToLook.y, pointToLook.z));
im using this code above to rotate my robots upper half turret to follow the mouse, right now it moves instantly but id like it to take time to rotate based on a rotation speed. i tried doing something like this but it wasnt working right, can anyone please point out my mistake? thanks
Quaternion turretRotation = Quaternion.LookRotation(pointToLook.normalized, Vector3.up);
partToRotate.localRotation = Quaternion.RotateTowards(partToRotate.localRotation, turretRotation, turretRotationSpeed * Time.deltaTime);
Maybe mixing local and world coordinates up if you're using mouse coordinates? Little rusty on this stuff so that would be my guess.
Otherwise looks fine to me
i tried using rotation and localrotation and neither worked correctly =/
Make sure you're feeding LookRotation a direction and not a point. Everything else looks fine.
The direction would be equal to the point you're wanting to look at minus your current position, normalized.
what is the best system to save position of items etc between scenes in android/ios? a json utility? binary save? do you suggest me to use any plugin? or its more easy? scriptable can save data but will be reset when app is closed no when a new game started really?
guh
I cant find Device Simulator under Preferences, even tho i installed it in packet manager?
Not a code question, but it's in project settings, not preferences
Have a additive scene that is always active, containing components that should persist.
Then just store it in memory in a component manager
If you need to persist between sessions, then you would start looking into storing the data as json or other formats (EDIT: and please do not use JSONUtility for this)
Hello guys. Please help me out. I made a scenemanagerscript to switch scenes. Gave the component to the button and the canvas the button is on and it worked. After doing some changes to the design, apparently the functionality doesnt work anymore. I cant find the issue
Any errors or warnings when clicking the button? Did you add a Debug.Log to see if the switch scenes function actually gets called? Not a lot of info in your question, only that you have a problem.
Yes its better to let you guide me to tell you what you need to know to help me 😄
Share any errors that your Unity console might display when this functionality fails.
No errors ill add the debug code to the script now
Otherwise just share the script and possible screenshot the component shown in the editor inspector
OK. I didnt change the script and it worked earlier. I dont know how to add the debug code, so ill just do that. In visual studio i can also press debug, is that sufficient?
As Micro Jackson mentioned, place a Debug.Log down. This can help a lot with understanding the actual issue. Place it at the start of LoadScene, and have it print out SceneName. See if this logs, and also logs the right scene.
sorry im new to this, you gotta tell me exactly how to write it
I get this error in console. Can it be because i changed the pixels that i cant press buttons?
You could look up the Debug log documentation to learn how to write it
Or go through the beginner scripting course in Unity Learn
It's pinned in this channel
Ok i did it but i ruined the syntax
!learn
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
Because you seem to have no idea how the context is supposed to be written
I suggest you learn the c# syntax before trying Unity. Otherwise you're learning two topics when you should have learned c# first.
I dont have the luxury to do that, but yeah
And please like the other people said, try to learn the language first.
Why don't you have the luxury to learn how to code 1st ?
I mean, it's not a luxury, it's a necessity
I'm afraid it's more a necessity than luxury. And apart from that, we would gladly help somebody with actual Unity issues, and not c# issues. We do expect everyone to know the basics of c#.
Sigh first week in Unity and I am already having a problem getting my sphere to follow my mouse.. Is this where I ask for help ? 😦
Im at a university where we learn both at once. Ill look into a lot of c# in my freetime thank you for the suggestion.
I added the debug.log, but in the console i only get this
if it is code related, yes. see #854851968446365696 for what to include when asking for help
and where are you calling that method?
here and here
screenshot your entire console window
Okay ill post >>> when posting scripts. I am just starting out in Unity. I honestly do not know how to make my sphere follow my mouse. My first language was CirPhyton and I was a begginer at it and im switching to #C.. idk im kinda confuse
show your code
its just this 165 times. i get no information about my scene script debug
and you have clicked the button?
And yes it used to work until i copied the button 3 more times, and changed the dimensions
i cant click it
in game nothing happens now
wdym you can't click it?
where do you have a line of code that says something like
LoadScene("myScene");
i click and nothing happens, its like the button isnt there
they've got it subscribed to a button's onClick event
then it sounds like an issue with your UI and not your code
select the event system in the hierarchy and pay attention to its preview window at the bottom of the inspector when clicking things in your scene during play mode. if it is not detecting your button when you click it, then something is probably blocking the button
he's got 3 buttons outside of the canvas
ah don't spoil it
which button is subscribed
Yes i have not finished those buttons yet. i only care about this button atm
then do this #💻┃code-beginner message
and ask in #📲┃ui-ux if you cannot figure out why your event system is not detecting your button(s)
Hello! I have written this code that detects if the Line of sight of an enemy collides with a player. If it does, I tell the enemy to move towards the position of the collision.
private void OnTriggerEnter2D(Collider2D collider)
{
if (collider.tag == "Player") {
enemyScript.playerFollower(collider.transform);
}
}
The problem is it only checks the collision once, and goes to the point of collision, but I want it to repeatedly check if the player is inside the line of sight and move towards it.
This probably means I have to approach it differently, but I can't think of a way to do it.
Any help is appreciated.
couple notes:
- use the CompareTag method rather than string equality to check tags. it is not only a (very small) performance gain, but will throw relevant errors when a tag doesn't exist instead of just failing silently
- use a physics query like a Raycast, OverlapCircle, etc rather than a child collider and relying on physics messages
The enemy must have a Rigidbody followTarget (or Transform, if Rigidbody is not used)
which takes a reference from OnTriggerEnter2D, and nulls it at OnTriggerExit2D (if desired).
Then, make code to Move Towards a Position (the followTarget.position) every frame.
is the Enemy Rigidbody dynamic or kinematic?
Rigidbody2D*
rainVisualEffect.SetVector3("Camera", playerTransform.position); - Value of name 'Camera' was not found
Visual effect
It is dynamic.
then #✨┃vfx-and-particles is probably where you want to ask
k thx
Moving by AddForce or Velocity?
their issue with their current setup is that they are using OnTriggerEnter2D instead of OnTriggerStay2D since they confirmed that it checks the collision once then not again
but they should still consider using a physics query instead of relying on physics messages
I used a function called MoveTowards
That one is designed to move a kinematic rigidbody
MoveTowards isn't even the rigidbody method, it's a Vector3 method. they are probably moving it via the transform if that is what they are using
Kinematic rigidbodies aren't affected by physics simulations. All movement has to be coded.
MovePosition is the Rigidbody method
ah wait
I misread
ignore my previous replies
MoveTowards is a Vector3 method
it should work
but still, made for Kinematic
The movement does work, yes.
I just had problems with the trigger only checking once, I know it is normal, but I am just trying to find a way to check repeatedly.
It will work, but if you introduce physics forces, there will be jittery movement.
If you aren't relying on realistic physics simulations from forces or collisions, then you can just make it kinematic.
What you said here makes a lot of sense, I didn't consider using OnTriggerExit2D. I think I will make a variable that defines if it is in the line of sight or not, then if it is, then move it towards the player in the update function.
Does OnTriggerStay2D check repeatedly if it is inside the area?
yes, but you should still use a physics query instead
Yes, though I don't think it triggers on Enter or Exit.
Depending on the game, trigger colliders can be used, but it is more optimal to at least include a Raycast, which will probably be necessary when walls are involved
I'd use a Trigger for the Range
and while in range, raycast towards player, to confirm Line of Sight
Hello I have a problem with DOTween. I have an UI element that I want to move to X local position set in the inspector.
transform.DOLocalMoveX(insideXValue, insideMoveDuration).SetUpdate(true);
I've set my insideXValue in the inspector to -300, but the object moves to -1260, why is that?) Screenshot is from runtime after the tween finish
@void jacinth PS: About the enemy movement
Either rework the code to use AddForce or velocity,
or simply make their Rigidbodies IsKinematic = true
so that the movement isn't messed up by physics forces like gravity
Got it, thank you!
Thanks so much for reply. I have a persistent scene as you say with my managers, and i load different scenes are additive yes, the info that i. want to save are position of items dropped or activated. So im testing right now if each gameobject (i only need it for around 20 items required for puzzle) got his scriptable info and when i load a new game i reset the info, i never has been used json, is better solution instead of using scriptable data for each item?
{
return Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, .1f, jumpAbleGround);
}```
This boxcasts returns true when my character touches the walls and roof aswell and not only the ground, anyone know why?
Seems simple enough to me, can't really wrap my head around why it should not work, i don't touch my collision box in any other way
are your walls and roof in a layer of jumpAbleGround
yes
there you go
your box is probably too large. it's the same size as your collider
why dont u just use raycast for this though?
It is the same size as my collider, and the collider collides into things, so the box shouldn't be too big
Ye i think i'll just do that
if your collider can touch it, then so can the boxcast
use an OverlapBox that is small and just at the player's feet. no need to actually cast it
Aight i'll check it out, ty
you can also use a little trigger collider on feet and use ontriggerenter and ontriggerexit
what programming program would you guys recomend? until now ive just been using notepad
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
what does IDE configured mean?
an IDE is the integrated development environment. aka Visual Studio. having it configured means it will provide error and syntax highlighting as well as autocomplete
how do i check if my player has collided with any gameobject in a gameobject array?
do you know how to loop over an array?
visual studio is asking for some microsoft thingy that i dont have
just make a microsoft account if you somehow don't already have one
yeah
well then surely you know how to check if an object is in an array.
also what is the purpose of this because there's usually a better way than checking if the colliding object is in an array
im trying to get so if my player collide with an obstacle it dies
wait nevermind i just accidentaly clicked on a pop up of microsoft ignite
check a tag
wait why is visual studio 13 GB?
because that's how large it is
if you hate having working tools you can use vs code instead
or if you don't want to get help with your code in this server you can continue using notepad
im here rn how do i check if it has collided with any go in my array
don't bother with that. just check for a tag
unless you want to have to add every single obstacle in your game into an array
nvm
how do i check for a tag?
if my collision has collided with a gameobject in that tag xd
Normally you'd just check the tag of what you hit. The collision object should have a collider property that's the collider component of what you hit.
so if(collision.gameobject.tag == "Obstacles")?
use the CompareTag method rather than string equality to check tags
Example of how to compare tag: https://docs.unity3d.com/ScriptReference/Component.CompareTag.html
You should lookup a tutorial on this though as it seems you are still learning the workflow. It'd greatly help you.
would i have to change the tag of every gameobject or can i just do the parent of that?
idk this doesnt work
the objects you are colliding with will need that tag, yes
thats basically then the same as putting them in an array
but anyways it still doesnt work
it is nothing like that
The difference is that with the array, you'd need to check every object if they were the object hit.. whereas this just checks the object hit.
because with an array you'd need every single instance of each obstacle in your array
true
whats the issue with this?
what hav eyou done to make sure that OnCollisionEnter is actually being called? have you put any Debug.Logs anywhere or used any breakpoints?
where? because i don't see it in your screenshot
put it outside of the if statement
also wtf censoring your log? lmao that's a new one
hahaha
oh and if you could stop sending screenshots of !code that would be nice
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
yup still no debug
i still have no idea whats wrong
have you gone through all of the steps in the link i sent?
@slender nymph @queen adder
If i have velocity towards the wall it still returns true in the air. If i make the overlap box smaller in width than this it works, but the setback being that if i am only standing on the corner of a tile i obviously can't jump. Will a raycast solve this issue?
yes
oh wait
that script is in gamecontroller
bruh
a raycast is smaller than an overlap box. so no, it won't solve that. but you can make the overlap box a bit wider if you need to. just don't make it so wide that it can detect objects on the ground layer that are next to the player
The issue being that on that picture, it is to wide to work, as it returns true if i jump towards the wall (Playing my landing animation)
So i can't make it wider
@slender nymph
To illustrate, it only happens if i have high enough velocity, the particles spawning around the player means the overlapbox returns true. So i geuss it's because the engine doesen't update fast enough?
https://gyazo.com/48e3bb3cb1c8987355024289fb845197
So the bounding box is within the tiles for a frame maybe
lol i just realized you can even see the frame where it happens
yeah looks like your collider is penetrating into the wall. that usually indicates you are not moving in a very physics friendly way
hey i have a problem wi visual studio, it's attached to untiy but there is no autocomplete
Ray cameraRay = cam.ScreenPointToRay(Input.mousePosition);
Plane ground = new Plane(Vector3.up, Vector3.zero);
float rayLength;
//Turret Rotation
if (ground.Raycast(cameraRay, out rayLength))
{
Vector3 pointToLook = cameraRay.GetPoint(rayLength);
pointToLook.y = partToRotate.position.y;
Vector3 dir = (pointToLook - partToRotate.position);
Quaternion turretRotation = Quaternion.LookRotation(dir.normalized, Vector3.forward);
partToRotate.localRotation = Quaternion.RotateTowards(partToRotate.localRotation, turretRotation, turretRotationSpeed * Time.deltaTime);
}
what did i do wrong here? the characters turret is looking into the ground instead of where the mouse cursor is
double check in preferences that visual studio is set as the script editor
i even tried to regenerate the files
@slender nymph I double checked my code for proper movement, seemed fine, switching the collision detection from discrete to continous solved it, thanks alot for helping out!
and let me guess, that "proper movement" is moving via the transform rather than with a rigidbody?
no, rb.velocity
Hello. I need help how can i make a raycast ignore a layer? A quick google search told me i need to put a ~ before the layer name but its not working for me. I made a new layer, put it on the player and refferenced it in the gunshoot script. when i raycast if(Physics.Raycast(gunCamera.transform.position, fwd, out hit, gun_range, ~pLayer)) and debug the collison name it still hits the player... and yes i named my mask pLayer because i found that funny. 
you need to turn the LayerName or Id into a LayerMask
and then use ~ to invert it
at the refference i used public LayerMask pLayer; this what you mean?
depends what you put in there
the layer that i made for the player called "Player"
so what is the Id number for the Layer 'Player'?
3
ok, so if you debug.Log the variable player it should contain the value 8
i don't really get it wym. why does ~pLayer simply not work?....
A Layer Mask is a bitshifted value from a Layer id so...
if you have a Layer Id of 3 the mask is 1 << 3 which results in the binary 1000 which in decimal is 8
Is pLayer a layer index or a layer mask
These are very different
show what you assigned to the pLayer field in the inspector
Sry, was busy.. so
and obviously put the Layer 3 "Player" on the player gameobject itself
Okay, so it is a mask. That raycast will interact with all layers except pLayer
It'll pass straight through any collider with that layer
thats what im trying to do since if i look down the player can shoot itself but its not working
now show the player object inspector
autocemplete is not working but visual studio is attached to unity, i tried regenerating the files and reinstalling
It is not configured
!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)
Inside the raycast statement, log the object that was hit and what its layer is
is this the whole obbject? Are the colliders on a child object?
Where are the colliders
it is, i installed and the unity extension, i tried also installing it from the unity hub, same result
Dead giveawway that you missed a step somewhere
they are child and they also has the Layer: Player
any fix ?