#💻┃code-beginner
1 messages · Page 522 of 1
if its saved into mysql from Unity, and you display it from mysql in another page. What exactly is the interop for on the webgl page
to get the highscore, maybe other statistics from the game
so Get Highscore from MySql then into Unity then into JS to show on the page? why not directly from mysql onto the page?
the log is not printing ?
I need to get the highscore, people can play the game on the browser and I need to get the score when they finish a run, then save it to the mysql on the server so it can be in the leaderboard
I mean I understand the usecase I'm just trying to understand why you need interop at all lol
if ur running it from the Editor how is it supposed to work?
because I dont know how else to do it
ok so the function does run but not on Web?
did you actually build to webgl ?
thats what i wanna know
I did
with this new code?
and it doesn't work?
what new?
nah
it does not
is it possibly an issue w/ the Javascript?
did you actually put the javascript file?
// Define the JavaScript function that Unity will call
ShowAlert: function (message) {
window.console.log(UTF8ToString(message));
}
};
mergeInto(LibraryManager.library, functions);``` this is in JSLIB.jslib that is in assets
hmm that looks diff from the page are you sure thats meant to be on the bottom?
mergeInto(LibraryManager.library, {
Hello: function () {
window.alert("Hello, world!");
},
});```
well, I can change it, but it should have the smae effect I think, give me a few minutes so it can build
ohh okay i see you passed the variable as functions, i guess it would the same then
this
UTF8ToString(message)
should probably be
Pointer_stringify(message)
according to documentation Pointer_stringify is deprecated thats why I used UTF8ToString
changed it to this, but still nothing
yeah its the same thing, forgot that you can store stuff in js without declaring type lol
well i'm just looking at my production jslib. also you're missing an autoAddDeps
whats that?
var functions = {
// Define the JavaScript function that Unity will call
ShowAlert: function (message) {
window.console.log(UTF8ToString(message));
}
};
autoAddDeps(functions, 'ShowAlert');
mergeInto(LibraryManager.library, functions);
what does it do?
weird. no mention in the docs
it exposes the ShowAlert function to the library manager
kinda important then...
🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.
📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!
💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.
For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting
nah
no, they just being lazy
welp
lol, nothing wrong w/ it 😄
didn't expect it to post my command, i don't know exactly how discord works
if bots can eat commands and not post them
what are u trying to do?
ahh okay 👍
still nothing
its acting dead like a mouse
does the javascript have to be in the index?
do you have any errors in browser console?
im just curious
never seen javascript being called via a unity script
jslib afaik is already in the unity build
you can add additional JS scripts to interact with if you add them to the index.html
all I get are these warnings, but I get these even when I dont have the jslib and things in the game WebGL: INVALID_ENUM: getInternalformatParameter: invalid internalformat
siiick
might have to give this a shot later
how?
it's not actualy javascript, it's called enscripten
https://paste.ofcode.org/JYDM5pZyMxaRzPVY2cuNWr this is the index it generates on build btw
wdym how, thats if you want additional JS interaction.
yours should work fine, you put a .jslib file in the plugins folder correct?
yeah
but it does not work...
what does your c# side look like?
hmm weird just tested it and works ok for me nothing needed
public class InteropJSTest : MonoBehaviour
{
[DllImport("__Internal")]
private static extern void Hello();
void Start()
{
Hello();
}
}
huh...
mergeInto(LibraryManager.library, {
Hello: function () {
window.alert("Hello, world!");
},
}
)```
how are you testing the WebGL btw
apache server on xampp
which compression method did you use btw
no compression since it is http
ok good good
I tested it with VSCode LiveServer plugin but doubt thats much different than xampp
Im using unity 2021.3.37f1 if thats useful to know
I'm on 2022 but I think its the same process
I just have no Idea why its not working
something wonky going on here..
what i always do is try
A Blank Scene, 1 Script with only that function in Start or something. And just export that scene, see if thats working. This makes it so you dont have to worry about anything else
@lapis totem This works
var Library = {
Message : function(msg) {
console.log(UTF8ToString(msg));
}
}
autoAddDeps(Library, 'Message');
mergeInto(LibraryManager.library, Library);
using UnityEngine;
using System.Runtime.InteropServices;
public class JSTest : MonoBehaviour
{
[DllImport("__Internal")]
private static extern void Message(string message);
void Start()
{
Message("Hello World");
}
}
I built it with just the test scene selected but its still showing the samplescene
it shouldn't . Just remove it if anything
are you sure you made a new build 😅
make it in a brand new folder then lol
OK..... I HATE UNITY now... 5 hours of tinkering just because it defaulted the build into an older version of the web HALF WAY THROUGH! I build at least two builds in the latest web directory, but unity decided to afterwards just build it into the old web directory, which had just a single number name difference compared to the new one. I AM DONE, thank you very very much for your help. I appretiate it a lot, time to sleep since its almost half past midnight now. Have a nice day.
now I feel bad for wasting your time...
ayooo..niiice lol
hey at least its not some weird bug or something. Good to know its working.
I didnt even think about that tbh lol i always built to new folders it slipped my mind to ask.
well, I have my project in a directory where I have multiple versions of it, essentially titled project_1, project_2 etc. In those I have a Games folder in which I was making the builds, I made at least two builds in project_4, but after that it seems that it was putting the builds in the Games folder of project_3 instead, and since it is just a single number difference I did not notice
Everytime I start my application in editor right now, I get about a 4,000 MS EditorLoop lag spike. This appears to only happen in editor and not on build. Is there any way to debug this to find out exactly whats causing it?
the spike doesn't say what it is inside editorLoop ?
turn on deep profile
4k ms is insane
DeepProfile is enabled.
oh yeah seems like editor loop doesnt have hierarchy, I must've misremembered
Hmm. Was able to track it down, partially. Seems like its due to some OnValidates that I'm using in Scriptable Objects.
OnValidate strikes again
I even avoid putting heavy stuff in Start and Awake because it has the same effects for builds
Heavy enough apparently. Guess I'll need to work on an alternative.
That or just manually add things.
isn't Reset better ? or do you need specifically after field chages /event
Honestly, I just need it on Creation of the asset.
Preferably though, when its being duplicated as well.
iirc there are other hooks/events for those that might work better ? its been a while since I touch unity editor coding
AssetModificationProcessor is one of them. I was just hoping to keep it simple.
Looks like OnEnable doesn't work either in this case. 😦 Guess I'll take the long root or just do it manually.
The Awake call seems to work/do what I want it to do, so, theres my solution I suppose.
I have a few virtual cinemachine cameras in my scene. How can I hide the white orientation lines in the Scene view?
Oh! nevermind, i figured it out
Vector3 newRight = Vector3.Cross(newCameraDirection, Vector3.down);
Vector3 newUp = Vector3.Cross(newCameraDirection, newRight);
cam.transform.rotation = Quaternion.LookRotation(newCameraDirection, newUp);
this ended up solving my issue, I should stop skipping math classes
trigonometry 😨
Should I add events in interfaces? For example I'm trying to add a Die event, so should I make a IKillable script that objects can inherit?
interfaces arent inherited
they are implemented
big difference
and sure as long as the event is a Property should be fine
What is the difference if you don't mind me asking
Also thank you!
once you "inherit" something you're stuck in that inheritance chain and you can't inherit more than one class, Interfaces are implemented therefore many can be implemented on a single class
eg
Cat -> Animal
cat is an animal but cannot be anything else unless Animal inherits something else
if you do implementation
like Cat , IEat, ISleep, IPoo, etc.
You can have many classes with the same implementations, without them having any other relation besides having those common implementations
My bad.
Ohhh, I see! Thank you very much! I understand a lot better now :)
Is it possible for me to use public class PlayaCharacterNormalLocomotionInput : MonoBehaviour, IPlayaHumanCharacterLocomotionMapActions without the need of PlayaControls?
what is PlayaControls and how does it relate to this?
Its the C# file generated from my PlayaControls input system.
I heard there's a way to do this
Anyone would volunteer to teach me how to make a fade screen after the button is pressed?
I'm new to Unity and just learned a few stuff today
google around, they have plenty of guides on this
How can i change unity's volume settings through monobehaviour code?
you don't use the generated C# file directly. at least, i haven't seen anyone do so. most use the input asset in conjunction with the PlayerInput component . . .
hello, does anyone know why this isnt working?
Vector3 transformAmount = -moveDirection * movementSpeed * Time.deltaTime;
obj.transform.Translate(transformAmount);
var trackIcon = obj.transform.GetComponent<campaign_friendlyTrackIcon>();
if (trackIcon != null)
{
trackIcon.destination -= transformAmount;
RectTransform movementLineRect = trackIcon.movementLine.GetComponent<RectTransform>();
RectTransform timeAndSpeedRect = trackIcon.timeAndSpeed.GetComponent<RectTransform>();
timeAndSpeedRect.anchoredPosition = new Vector2(movementLineRect.anchoredPosition.x + 60, movementLineRect.anchoredPosition.y);
}
transform.translate is moving it a different amount than manually addiing it to a vector3 does, how come?
ive been struggling at this for a bit
Ahh
Try logging your position before and after translating
Any good resources you guys know of to learn physics and mathematics specifically for game developement and computer graphics?
Books have been used since a few thousand years back. They are cool things 🙂
For computer graphics, there is little difference in that math vs. standard math. Just learn about vector spaces and how they are represented
checkout freya holmer for maths . . .
For computing (and graphics) discrete mathematics, vector and matrix spaces, set and collection theory and core algebraic principles are key. For physics simulation you need an understanding of calculus and geometric funtions.
though you don't need to know physics. just use the physics engine: colliders, physics methods, etc., from unity . . .
It IS useful knowledge in general though...
that can be said about pretty much anything. unless creating something specifically accurate in physics, theres not much application. might as well claim it is useful to know rocket science
most can be solved using first year math. especially since most operations needed are already built in by unity
there isnt gonna be an all encompassing answer here. computer graphics is already widely different from "basic math required for game dev". Also the level of math we're talking here matters a lot.
Basic math imo would just be stuff like vector math (adding/subtracting, dot product, normalizing). This stuff you can really just look at the first results on google, khan academy was always pretty good. While itd be good for you to know how to calculate these things, unity already implements it.
If you're looking for advanced physics or math, this would imply you're making something pretty niche. Either look for devlogs of people doing the same, or hit the books/papers on the real math to understand it properly.
Any stem book made specificalpy for gamedev and cg that you can recommend?
can I copy things from one scene to another?
and after creating new scene how do I access to old scene?
Hi there.
I changed from VS 2017 to VS 2022
I have this minor problem, whenever i create a new script, intelissense stops working and i need to close VS and open it again to make it work again.
As I say, its a minor thing, but is there a known fix for it?
only one scene is active at a time. when a new scene is loaded, the old one—and everything within it—is destroyed . . .
for that, you can easily google how to load a scene. there are tons of answers . . .
Considering you didn't share any info, we don't know
I made button
I would assume that the method you try to access contains parameters
Share the button, share your !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.
Until then, we don't know
chatgpt said I can make it without code
Your mistake is relying on ChatGPT for this
using unity ui
I'm trying to call another scene I guess?
What does "call another scene" even mean?
I'm making menu button that loads scene with game
So how do you load this scene?
I'm struggling to understand why it has to be so complex
You need code for that
@foggy tundra
This is how mine looks, I added a gameObject with my script attached
I use godot and it does involve one line of code
It's not complex. Your issue is that you are relying on ChatGPT instead of just learning how to do it
Also, loading a scene can be much more complex depending on your needs. It's a process requiring code, like anything else in a game
Nothing about it is complex. If you looked for a tutorial on this rather than ask the spam generator, you wouldve seen the code is also basically 1 line.
I couldn't find simple tutorial, sorry
I suggest you
how to load another scene, and take a look at hundred examples that do exactly this
You're not the first person that wants this
Once you have something and it still doesn't work, feel free to come back
And please get rid of ChatGPT ASAP until you have a grasp of how to do at least basic Unity
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneLoader : MonoBehaviour
{
public void LoadScene()
{
SceneManager.LoadScene("Level2");
}
}
If you found this video helpful I would really appreciate a small tip so I can improve my video quality...
just typed load scene button in youtube plz xdd
This question generally just feels very lazy, I doubt they tried
Its probably possible to do it through a Graph without code
I did as in video and mine has no functions as in video
is the function public?
I don't know
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Did you drag and drop the correct object?
Watch the video again and pay attention to what they do in the inspector.
no, I dropped wrong object
it has menu now
let's see if it works
ok I can't load that scene because it's mpt added to build settings, but when I go to build settings and lick Add Open Scenes, nothing happens
drag the scene from the project files to scenes in build
Make sure the scene is saved.
instead using the add open scenes
ok it works
i've ended up loving this thread xd i'm on the edge of my chair rn
thank you

sorry to be annoying I just been working with godot for few years and unity is very confusing for me
Please prioritize configuring your editor as Bawsi mentioned
I'm trying to set a GameObjects MeshRenderer material to use a material I made, but it can't find/load it. Any suggestions?
headModel.GetComponent<MeshRenderer>().material = Resources.Load<Material>("Assets/Transparent.mat");
Are one of the folders names Resource?
No. I tried putting it in the folder called Resources, but I guess I need to use just Resource.
brb
Resources should be correct i think
Nope. Still not working.
try changing to "Assets/Transparent"
Got it to work. I had to remove the file extension.
Thank you guys.
if I understood correctly, the code outside the "start" and "update" functions does not execute without being called (like in the csharp console without unity) but in this case why can I initialize my variables outside.
I'm very new to unity
so you have the start function nested so it will not do anything
not sure if your print("hello"); will be compiled
put it outside the print function and put the print function inside of it
looks like an error
it isnt nested, check the brackets
he just indented it
Start is member of printing
Because your !ide is not correctly configured to tell you that this is not correct behaviour. Your variable declaration is fine, but the method call is not.
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Once this is done your editor will inform you that print() is not allowed on class scope
looks like he is in sublime text

Then I suggest they either switch to Visual Studio or Rider
isn't start a member of monobehaviour not the class printing?
yeah it looks pretty much the same
In this case it is part of printing which is inheriting MonoBehaviour
I'll assume they definitely have not correctly configured their editor, especially considering the inconsistent casing in the class name will make Unity ignore this class altogether
public class printing : MonoBehaviour
{
int number = 12;
// Cant place functions here
void Start()
{
Debug.Log(number);
Debug.Log("hello2");
}
}
Try formatting your code with indentations like this, makes it easier to read
Printing
why we can't place function outside of Start or Update ?
code runs only in functions
so typing anything thats not declarations outside of functions makes no sense and wont compile
I dont know any other answer than its designed that way.
Just assign stuff there
This is an OOP language. It doesn't run from top to bottom like some languages.
Your code must be contained in methods, or in initializers
I suggest you learn basic C# first before delving into Unity
That's what i'm doing
So, there is a Main function inside of Start or Update function ?
No you're not
You're trying to learn C# alongside learning Unity
hello
Unity is vastly different in how C# works and you're going to have a hard time if you try to do them both at once
whats the difference between this.transform and just saying transform
I'm trying to understand how classes works
So I suggest you close Unity and make a basic console application at the very least
ok i'll do that
Nothing
this just ensures that you point to the class when you get something
oh ok
The only reason for this is when you are bad at naming things and you want to make sure you don't grab a local variable, or something
so if you make a variable named transform, you have to type this.transform otherwise tou are reffering to the variable instead of the component?
No
If you make a new variable tranform, then that replaces the old one
Your compiler will inform you of this
You can get the old transform through base.transform, or just don't name variables that already exist
If you truly intend on replacing it, then you should use the new keyword with it.
However, the proper way is to have virtual variables, and to override them assuming the signature is the same
i understand
is it possible to give each npc worker in a game there own inventory so they can go out collect resources and then return with them.
Yes
do you just add a inventory scriptable object to a prefab for the npc ?
That depends entirely on how you define "worker", "inventory" and "resource"
well i want to have workers i can send off to collects ore, woods, hides etc that you can use for crafting. what im looking to do is give them a specific amount of storage space to go fill up and return with what they got.
for example i want the player to be able to hire a miner to send off to collect iron ore or some other kind or resource you would get from mining
And what have you done in code to define any of this so far
Nothing just trying to figure out how to do this. All i find online is simple player inventory systems with a ui interface but nothing to do with what im trying to do. At the moment all i have is some scriptable objects for some resources and items to craft, a recipe SO and one for a worker with item slots so you can give it gear to boost its capabilities
Im trying to setup inventories now so i can work on a crafting system to pull stuff from base inventory to craft with
If you have a component that defines a worker, and a script that defines a resource, all you really need is a list of resources on that worker component
So just have that with a max capacity variable then so they only pick up what they can put in there im guessing
Whatever you need it to do. You aren't going to find a tutorial that does exactly the thing you need it to do, so you're going to have to design your own system that suits your specific needs
Yea i figured i would, was just unsure how to go about it
Will figure it out sooner or later
Guys
How do I refer to a script attached to a game object?
Hello, im trying to get the distance of my player and a gameobject with a boxcollider. When I use Vector3.Distance(), it tracks the center of the object and not the whole. any tips?
Vector3.Distance doesn't "track" anything, it just calculates the distance between the two vectors you supply to it. but it sounds like you're just giving the transform.position of each object when you want a point on the collider face?
Probably a raycast from the player, then you can use the distance of the RaycastHit, which would get you the distance to the point it collided, which would be the edge
appreciate it
If you need the edge-to-edge distance, one thing you could do is raycast from the player to the collider, then raycast back from the contact point, back towards the player. Then that distance would get you the closest approach distance from edge to edge
(Assuming neither of these are simple shapes like boxes or spheres where you could use bounds.width or radius)
Hi everybody. I faced such a problem that the sprite of the weapon does not want to rotate with all the added scripts and is in the same position, despite the fact that in another similar project, where everything is done the same way, the weapon rotates without any problems. What could be the reason?
Errors in the console are also not highlighted in this regard.
you would have to show us what the object hierarchy looks like, which scripts are on which objects, and the inspectors for the scripts.
1 min
but it seems to me depending on the execution order, only one of those two scripts is going to work at a time
assuming they're both on the same object
they are both trying to modify the rotation of the same object
is the script on the right thing?
Yes, that's right. Everything is generally correct because in the same project, where everything is written and fixed in the same way, everything works.
Or I don't see something where there is an error. But I've already rechecked the scripts 10 times.\
show a screenshot of the inspector of the object that's supposed to be rotating
maybe you forgot to save the scripts
checked it , saved it again, everything is the same
Hey, we are in a group of 8 devs, all first time unity.
We are discusting whether or not the monobehavior scripts that we create should end with Script
So PlayerMovement or PlayerMovementScript
What is most commen / code convention
I don't think it's necessary. It's more likely that you'd want to have prefix/suffixes for other things, like Interfaces leading with I
Probably a bulk of your C# files in a Unity project will be MonoBehaviours, especially if you're using composition extensively.
Absolute blunder to add Script at the end of everything. it's useless noise. You know it's a script already.
That's like calling things xxxClass
If anything, appending Behaviour or Component makes more sense, but it's still unnecessary
It also doesn't conceptually make sense. The thing you would be referencing if you have a field for that type is not the script.
PlayerScript p; is a reference to a specific player. Not a script. So Player p; makes so much more sense.
most people go with the former, as it is not necessary to have script at the end of every script name
PlayerScript pVariable; // comment: variable of type PlayerScript
Hm, a little ambiguous
PlayerScript variableOfTypePlayerScriptThatRepresentsTheCurrentActivePlayerInTheScene;
thats horrifying
I usually just do _Playerscript,player, movement, etc (I believe) as the variable name, its probably not the best way to do it but I have zero clue 😁
Hello everyone, I have created a little main menu in that I can hover over START, SETTINGS and QUIT and it will go from transparent black to yellow when I hover over it. When I click settings and then my BACK button, then hover over START and QUIT again it no longer has the animation, does anyone know why?
Is there an event system in the scene?
Yes there is
Is it still there after the buttons stop being responsive?
Why do I get this
Shader error in 'Shader Graphs/Master': Couldn't open include file 'Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/Lighting.hlsl'. at Assets/CustomLighting.hlsl(10)
When the written line is this, pointing to the folder which contains lighting. I dont even see a lighting file in "ShaderLibrary"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Lighting.hlsl"
yes it is still in the hierachy
Are you getting any errors in the console?
I keep receiving a warning message of "There are 2 audio listeners in the scene. Please ensure there is always exactly one audio listener in the scene." if this is a problem
no
good - select that event system object and watch the Preview tab in the inspector as you do your stuff. The preview tab will show what you are mousing over.
Your buttons are probably blocked by some invisible ui element or something
okay i will try now
or possibly you made them uninteractable while the other menu was open
and forgot to reverse that
private void OnMouseDown() {
mouseDifference = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition) - (Vector2)transform.position;
}
private void OnMouseDrag() {
transform.position = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition) - mouseDifference;
}
private void OnTriggerEnter2D(Collider2D other) {
if (other.gameObject.layer == 3) {
CheckoutScript.checkoutValue += value;
Debug.Log("Checkout detected");
}
}
I want to create a really simple Game, where the player pick up coins and drag them to the checkout filed. The Coin is a Collider2d set to trigger. The checkout is rigidboy and collider2d. Is there a fault in my code, with the mousedrag? When trying the trigger doesen't trigger. But the coin is moveable. This is the Code Script
If you want to differentiate Monobehaviour from non-monobehaviour, then I'd argue you end with Behaviour
But honestly I dont think this should be done. Just call them controllers, managers, stuff like that
show the setup
I cant see the components, why are they cropped
idk.
- every screenshot should be full window
- save your scene as something other than 'SampleScene'
Thanks everyone for responding !!
I will remove script from everything since i think there is 1 clear winner XD
where is collider on white area
is it a Rigidbody? or a Rigidbody2D
2d
does static work with triggers?
to see if its getting called?
im not 100
i wuld think it could cause probs
hi all! I am having a little bit of trouble getting scene transitioning to work, my scene scripts don't seem to work at all. Any help would be appreciated, thnx
here is my current layout rn, the trigger for the scene just doesnt work
This shows nothing useful
Show how you've actually set up your triggers and code
i am really new to unity, so if you need to me provide something specific, lmk
o oke
heres the code for the scene transitioning. cs
I mean, you've set it up to work (how you think it should work), so naturally one might show that instead of just a gameplay screen.
how do i screen record?
Unless of course, you think putting the object named Challenger into your scene is all you need to do.
ok now show the Player object inspector
i dont have game bar or nvidia highlights on this computer
OBS or ShareX or etc
well then you cant
rip
You don't need to record your screen, take a screenshot of how you set up your character's rigidbodies/colliders, etc.
^ code/ heirarchy/ inspector of relevant objects is normally enough
player already missing trigger / collider
you sure? i have the layers
I can trust my eyes
solid objects, interactables, and battlezone
we're positive
theres no children objct of player.. and u dont have any 2D colliders
i added a 2d collider to the scene transition, not the player
why would you check if other.isTrigger if other doesnt even have a collider
you can't detect collisions without one
so wait do i just add a box collider 2d to the player
my npcs have them
if so.. then yes
if you plan into triggering something you need them lol
player is there
ya, but it doesnt hav a collide.r.
idk how to make it detect it
it'll never trigger that function
how can it detect a player without collider though
i think
it says collider2d
on there
also at least 1 rigidbody is needed
where
huh?
on trigger enter 2d collider 2d other
the method EXPECTS a collider2d
ur object doesnt have one
thats the "incoming" collider
again im really new to unity so i have rly no idea what im doing
Yes, that is a reference to the collider of the other object you hit
and help would be appreciated
you never have anything incoming in the first place
😓
OnTriggerEnter happens when this object collides with another object, and if at least one of their colliders is a trigger
Collisions, by definition, require two colliders
so how would i fix this? asking the question
for my scene transition code
would i add something else
start by giving your player a collider?
If you want to detect a collision with the player, the player needs a collider
whatever shape you want to on the player
Whatever shape you like
scripts and colliders are not related
collider is a specific component to give your object a "shape"
also at least 1 rigidbody is needed between the 2 Colliders
like this?
sure, if you want it to be solid and not a trigger
so click isTrigger?
Then you should check the box that says Is Trigger
i was thinking if the fkn
scene transition was a trigger already
the player wouldnt need the trigger
It would likely still work
yep it still doesnt work
That's why we asked if you wanted the player to be solid
do you have at least 1 rigidbody ?
because it could be solid, or it could be a trigger
i just added the box collider
so thats a no
i need a rigibody 2d now?
A rigidbody is required on at least one of them
alright
dynamuic, kinetic, or static
so i can give the player a rigidbody
sure
alr i just did that
either one
which one btw
Which one do you want?
idk what they do
i know dynamic for some reason slides off the screen
probably kinematic
blegh it still doesnt work hmmm
rigidbody must be present on atleast one object to detect collisions / triggers
ill try kinematci
public class DetectPlayer : MonoBehaviour
{
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
Debug.Log($"Player detected: {other.gameObject.name}");
}
}
}
should i set collision detected to continuous
not necessary here
since you're not doing fast moving bodies
How are you moving the player object
this is my second scene btw, dunno if i should do anything here
arrow keys
show us the movement code
Translation is gonna be problems when detecting physics collisions
probably a transform since they never added rb
moving transforms = same as teleporting
heres my code for player controller
yea, thats not gonna work for accurate collisions
You cannot use transform.position = Vector3.MoveTowards for accurate coll
you can switch it to rb.position tho or rb.MovePosition
well, you sorta have to..
Moving by setting position is not going to detect collisions. Use MovePosition instead
https://docs.unity3d.com/ScriptReference/Rigidbody2D.MovePosition.html
then no accurate triggers for you
so change transform.pos to rb.pos?
where can i hire game devs?
here yes you can also put rb.position
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
ya, it shouldnt be hard.. isntead of using transform.position change it to rigidbody2Dreference.MovePosition
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
but the main movement is the one with the MoveTowards
indeed
alr
also it should be moved to FixedUpdate
wait thats a coroutine, replace yield return null with yield return new WaitForFixedUpdate()
Guys
I've looked everywhere and I can't find it. What I found didn't work
How do I place the circle in front of the square?
are they sprites?
Yes.
UI.
well, UI is images..
order of hierarchy
draws last = always ontop
Where?
rb.MovePosition(Vector3.MoveTowards(rb.position etc.
hello
Oh...
its the Order of ur Hiearchy that controls UI elements
Ok
i ned help its dosent go pass 2 lives why?
Nice
Tks
⏬
📃 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.
hmmm im gonna try something else
why ask help if you're going to do something else..
UI uses Hiearchy Order
Sprites (2D Objects) use Z position / Sorting Layers/order
3D just clips
no im using the help im just
figuring out if like i can get away with something else
i want help dosent pass 2 lives Why?
what the hell is the point in doing that?
do you want it fixed properly or not
yeah i do but im testing something
annnnd it doesnt work
figured
thats a theory out of the way
literally a waste of time lol
it takes years of trial and error to know what actually works and what doesnt
fair
im doing this shit for college
im prob gonna get rly frustrated
seems like ur variable.. Lives applies to this script..
if u destroy it they're gone..
well its not somethin you learn overnight 🤷♂️
if u create a new one.. its back to default values
thats what some people make it out to be
i used to be a nintendo switch modder and it was difficult
also you're jumping straight into diffcult things without proper basic fundations
everyone made it look so easy
i had to spend hours looking at raw assembly
thats all i was told to do
Fighter Pilots make flying jets look easy too
C# is a little easier but not rly
code is important but knowing the components and how they work is more important
the problem is i dont rly
i used a youtube tutorial that didnt explain swapping scenes but helped w everythinge lse
yet
yes Im aware, thats why you should build up instead of diving straight into deep end
pro-tip.. you'll never find a youtube tutorial that does everything exactly the way you need
gotta learn to adapt.. use bits and pieces of many tutorials
and add em together
tutorials just says "copy this" and you do it, its not really explaining most of the time why that is, best used later on when you have more knowledge
the idea when the animal goes outbound i lose live i lose just 1st live but icant lose more
well iunno
!learn most importantly.. for the fundamentals
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
college on unity?
ive applied to several schools w comp sci and coding majors so i hope to learn shit
you should probably use a seperate gameobject like a GameManager that controls the lives
so its always in the scene
no just coding in general
again i want to learn what shit actually DOES
and everything is based off of the gamemanagers live values
most computer science graduates have no clue how to code a proper game / app
no im not in for comp sci lmaooo
the theory is good but they have no practical experience.
its part of my desired major but game design is my main focus
and game design has stuff like ui, music, coding, level design, etc
school just teach you big heady concepts and barely any true real life coding experience
and with the set of classes im getting i hope it helps
i keep the outbound make sprate script just for decreesments how do i conncet the out bound whit the gamemanger
this doesnt work the way u expect tho.. you Destroy the object.. including the script that sitting on it
how u ever plan on using that to count lives when u destroy it constantly?
reference it somehow..
can i ask if is there any references i can see to get the idea
yes but school is not some magic formula of knowledge, you have to be naturally interested/curious to learn more even if its on your own.
the main difference is schools are structured to ease you into complex topics, doing it on your own, you have the same exact resources but control your own pace
which makes it diffcult to do things in proper order
Choose the best way to reference other variables.
heres a page that shows u many of hte ways u can reference scripts or other objects
Singletons would be great for a gamemanager that tracks lives
(only ever have 1 instance of it) all ur gameobjects could ask it for the lives count
they'll all match
bro does anyone know why my OnTriggerEnter2D just like isnt existing ive got a monobehaviour class and tryna make it have collision logic with a trigger and when i try use any collision stuff it only comes up with the Unity.visualscripting function
becasue you dont have Unity Snippets 🙂
welcome to VSCode
I need to make a PR request for this, using an extension for this is ridiculous tbh
fr i wouldve literally had no clue what to do lmao
you could still type it out long-hand 😉
yeah its weird that microsoft made this and forgot about snippets
not like unity gives a shit about VSCode since they dropped full support at some point..
yet most of the employee videos on YT from unity are using vscode, aint that grand lol
also how to i check if an object has a specific component smt like gameObject.hasComponent<component> or do i just do like if(gameObject.getComponent<component>){ // code }
sure or TryGetComponent(always preferable because it has an included null check)
alr
TryGet OP
btw any Component has access to other components on gameObject and transform
so collider.TryGetComponent also works etc.
is there a way using like the leen tween library or smt where i can like make it so a range of numbers is converted to a range of colour so like when this variable is 10 the colour is green and as this variable gets closer to 1 the colour goes more and more red
i remember doing smt like that with LeenTween.value() i think a few years ago
idk tho
ya, could do that with a lerp
public void ChangeColor(int currentValue)
{
Color startColor = Color.green;
Color endColor = Color.red;
float t = Mathf.InverseLerp(minValue, maxValue, currentValue);
Color newColor = Color.Lerp(endColor, startColor, t);
}```
ive done that but now when currentValue gets to minValue the colours alpha just goes to 0
also wanted to make it interpolate from green to red with 10 to 1 and when currentValue = 10 the colour is green which is good but when currentValue is anywhere from 2 to 9 the colour is just a flat yellow and doesnt change and then when its 0 the colour disappears
sorted out the colours inbetween
but it still goes invisible when currentValue is 0
Hi, I want to implement a ball trail like in the reference video, varies its shape and helps to better simulate the “elevation” of the ball. I currently use AnimationCurves and multiple keyframes in script to simulate the ball's altitude by scaling the ball. ballscript fragment: https://hatebin.com/aznqgequim (1st video is the reference I want to achieve, 2nd one my game)
Ah, actually yeah I get what you're doing with the keyframes, but I feel like that's something you already have information from seeing the ball shrink in your version, which seems like something you can plug into the TrailRender curve here
make sure the red color has its alpha set to 1 . . .
void Flip() { facingDirection *= -1; transform.localScale.x = new Vector3 (transform.localScale.x * -1, transform.localScale.y, transform.localScale.z); }
Assets\scripts\PlayerMovement.cs(34,9): error CS1612: Cannot modify the return value of 'Transform.localScale' because it is not a variable
how do i fix this?
you should just be able to assign it a new float directly instead of using a new vector
Vector3 newScale = transform.localScale;
newScale.x *= -1;
transform.localScale = newScale;```
or transform.localScale = new Vector3(transform.localScale.x * -1, transform.localScale.y, transform.localScale.z); }
thxs but i just realized (after a half hour) that i dont need the .x on the transform.localScale.x = and that it should be transform.localScale =
that will work
same thing commonly happens w/ rigidbody velocity.. rigidbody.velocity.x = 5; <-- error
rigidbody.velocity = new Vector3(5, rigidbody.velocity.y, rigidbody.velocity.z); you tend to create a new vector if/when ur wanting to modify just 1 of the properties
yeah as transform.localscale.x or rb.linearvelocity.x are floats I believe
yup, many of the common things new game devs run into are like this now that i think about it
Colors / materials was a big one for me
why do i need to make a copy of the material to change the texture!
public static void SetX(this ref Vector3 vector, float x)
{
vector = new Vector3(x, vector.y, vector.z);
}
public static void SetY(this ref Vector3 vector, float y)
{
vector = new Vector3(vector.x, y, vector.z);
}
public static void SetZ(this ref Vector3 vector, float z)
{
vector = new Vector3(vector.x, vector.y, z);
}``` extension methods lol
couldn't you directly assign the X/Y/Z of a transform like so?
float Xscale = transform.localScale.x;
Xscale = anyfloat;
Or do you have to assign them again with the actual vector like you did above
I'm trying to understand colliders and bounds a bit better, but this one's breaking me - is there a way to get the topmost, frontmost and sidemost points of a collider?
when you declare a struct its essentially a value type.. meaning when you assign a struct to a variable you're copying the entire value, not just a reference to it..
for example in a Vector3 when you try to modify a specific component like the .x you're not changing the existing instance, but rather creating a new instance with the modified component..
Vector3 originalScale = transform.localScale; // Copy of the original scale
originalScale.x = newXValue; // Creates a new Vector3 with the modified x
transform.localScale = originalScale; // Assigns the new Vector3 to the Transform
while Transform is a class, its localScale is a struct
blabla immutability of structs
so you have to make a copy of it then use that copies X/Y/Z values and then assign the original with the copy again, I totally forgot about the copying instances of structs and classes
yea, you have to create a copy, modify that copy and assign it back..
Hello, I'm having a problem where the player isn't able to jump in my webgl build, but it works perfectly fine in the unity editor. I am using the new unity input system and I'm pretty sure input is working properly but the velocity isn't being added. The video shows how after clicking or using the spacebar, the prompt goes away and the game starts, and the bird falls and then collision is detected and the game ends. I can't jump in the webGL version though. Here is the playermovement code: https://hatebin.com/amqphitpzw
where does OnJump() get called?
In the playermovemtn script
its using the new input system
it also gets called in the promptcanvas script: https://hatebin.com/yjhghtvqbq
That just makes the prompt dissapear.
this code causes a slight stutter when the player starts pressing on the screen, and another stutter when the player releases
ive noticed a similar stutter in the chrome dino game
not sure if its a browser or device issue bc i tested it on multiple devices and it still stutters ( this only stutters on mobile not pc)
{
HandleInput();
}
void LateUpdate()
{
HandleCamera();
}
void FixedUpdate()
{
ApplyPhysics();
RotateTowardsVelocity();
}
void HandleInput()
{
float targetGravity = Input.anyKey ? -3.4f * Gravity : 3.8f * Gravity;
rb.gravityScale = Mathf.Lerp(rb.gravityScale, targetGravity, Time.deltaTime * damping);
}```
any1 know a fix?
Is it a performance stutter or a logical one?
seems like performance
Then use the profiler to identify the cause.
ok will try
I don't see any issue with the above code. Perhaps it's to do with the ApplyPhysics method call. Try commenting that line out and see if the performance improves. Either that or the RotateTowardsVelocity method call.
does anyone know why this enemy would appear hovering over the ground, but be placed properly when the game starts?
idk if its something to do with animations or what
it appears the root/pivot of the character (normally at its feet) is centered at the navmeshs center point
move the character model down until it fits the navmeshagent (capsule collider)
not really code related either #🏃┃animation #🤖┃ai-navigation #💻┃unity-talk
if I do that, he appears in the ground when the game starts
I just tried it
it's as if the pivot changes or something
its not using root motion is it?
how do I check that?
Hello! Im working in my first Game Jam I cant finish understanding somenthing, im trying to do a interactible, but it doesnt detect the collider as intended anyone could give me any advice? (The console wont recognize anything)
what's the hint the IDE is giving you with overlapsphere
This you mean?
ooh it's asking if you want to do non-alloc prob
Did you debug that the input is working first off
Next -> check if the collider array is ever not empty
Do you mind If I add you and ask you in VC?
that sounds like effort
Im sorry, I just dont know how to check if the collider is ever not empty
What you have there seems fine, and since you're not filtering out layers it should be easy to debug. You need to start debug logging each step, or step through it using the vs debugger
So, check that the input is working, and throw one into your foreach that it's actually going into there
Ok
So I did this changes to know where its not responding and I feel that the results confused me more, so everytime I press E it checks for colliders twice, but when it detects one it only checks one
I feel more lost then when I started
It's not checking twice, it's detected two colliders here so we can say that works
so with that known, we can say that what you're trying to detect is not*** an Interactable
Log the elements of the array?
Change ("Collider array") to ($"Collider: {collider.name}", collider)
This is what I get when next to a interactible
And when you click on the log, which object in the scene is lit up?
And this is when im away from it
so it does work>? 🤔
A bunch of items, floor, walls the interactible itself
Show your current !code using the proper format
📃 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 it must be the second code thats not working correctly?
ie the Large Code Blocks section not the Inline Code section
Click on one of the links provided by the bot. Copy and paste the contents of the script inside the website. Press the save button on the site. Copy the URL and post it here - it should have changed.
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerInteract : MonoBehaviour
{
private void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
Debug.Log("E was pressed");
float interactRange = 2f;
Collider[] colliderArray = Physics.OverlapSphere(transform.position, interactRange);
foreach (Collider collider in colliderArray)
{
Debug.Log($"Collider: {collider.name}", collider);
if (collider.TryGetComponent(out Interactable interactable))
{
Debug.Log("collider detected");
interactable.Interact();
}
else
{
Debug.Log("Collider was not detected");
}
}
}
}
}
Like that?
using UnityEngine;
public class Interactable : MonoBehaviour
{
public void Interact()
{
Debug.Log("Interact");
}
}
So when E was pressed, it detected the Wall, Floor, Places deleted, Cube and a few other objects.
Yes thats correct, but it didnt get the component and run the second code
Which object where you expecting that wasn't listed?
The component from which object?
A cube im testing with
This one
So click the message with the Cube once and see which object in the scene is lit up (yellow)
It should flash once
is there a way to instantiate an object as a child without changing it's scale?
I did
So is that the Cube object?
It should have been named Cube
And it likely did not have the Interactable component.
You could opt to use the parent constraint component to associate objects together without parenting. Else you may have to undo the scaling set by the parenting.
Yeah sorry I have it as wall(38)
Wall was valid
What's the issue again? How did we come up with the assumption that it's being checked twice?
no it was just not giving the interact, now it is
IDK how or what change made it work
Its just working as intended again
i think that'd cause more trouble in the long run
When you child something on the editor usually it'll try to keep the original size by changing the local scale for you. I think adding the constraints is probably the best idea if you do want to keep it child, but honestly I think you should reconsider the hierarchy and instead make this child a sibling
Hello, I'm having a problem where the player isn't able to jump in my webgl build, but it works perfectly fine in the unity editor. I am using the new unity input system and I'm pretty sure input is working properly but the velocity isn't being added. The video shows how after clicking or using the spacebar, the prompt goes away and the game starts, and the bird falls and then collision is detected and the game ends. I can't jump in the webGL version though. Here is the playermovement code: https://hatebin.com/amqphitpzw
Make dev build, log the input, check for errors in the browser's dev console
Meaning, two consoles. Dev build provides one, and pressing f12 usually brings one up
Wow I didn’t know you could do that, I’ll try it and get back to you
how would I add value to a int through script
Like, for everytime I do "Action" it adds 1 to an int
Like say I wanted to make a basket ball game with an int keptScore. If I make a goal, keptScore adds 1 to itself
what have you tried? did you search online? i only ask because this is the basic of basics. it's impossible not to know how to do this if you went through any intro or basic c# tutorial . . .
I don't know what to search, I just needed help if someone could tell me how to make this work or get me a link to learn how to do it
Kinda almost seems too simple to answer...
You're just asking how to add 1 to a number?
an int, yes
myInt += 1;
in script
Short for: myInt = myInt + 1;
+
Hello devs... who are using UNITY 6.26f1? Try please to insert sprite into image component... is it only me cannot insert imported sprite?
Is your image file imported as a sprite?
yes..the weird thing is that in Raw Image i can insert
Show the inspector of the sprite asset
one sec
rawimage takes a texture/sprite
image only takes sprite
look i know... watch my video
tried
are there any other scripts attached to this GameObject?
you can also try assigning it in code
nothing
code ref to sprite cant assign too

vid disappeared while i was looking at it . . .
It can't take a sprite sheet
yesterday downloaded Multiplayer sample there was not working shaders at all, today completly new project and this thing with sprites
Your sprite is set to multiple
I recording a new one
You'd need to drag in one of the sprite sub-assets, or use a non-sheet sprite
let me record i will show
i think smth in the sprite settings may be wrong. i couldn't finish looking at the vid . . .
wait a minute please setting up to record
A screenshot is fine
could you show your sprite import settings again?
earlier digiholic said that your sprite mode is set to Multiple, which could cause you not to be able to assign the sprite
set sprite mode to single and test . . .
multiple means you need to select a specific sprite from that spritesheet, not the sheet itself . . .
How does your image look like?
i know....but for some reason i just imported and changed to sprite and it automaticaly change to multiple
image like image nothing fancy
Ah yep then that's a single image
You only use multiple when working with a spritesheet
Look i know this, and sprite editor etc.... the thing is after import you click to change to Sprite...and it automaticaly goes to multiple (previously it was default single)
There's probably a way to change it in your importer preferences
Anyway, thank you all. will see in import settings
Does anybody know why my buttons are at the bottom like that? I want them to be in the midde.
make them a child object of the rectangle they're supposed to be in
and make their position relative to the center of that rectangle by changing their anchors
Can anyone explain why this code only gets input when the pause menu game object is active? I cant figure it out for the life of me
Because Update is not called on inactive objects
Guys do anyone know how can I use github with unity?
By just using it, there are no specific things you should make sure
The only thing is having a proper GitIgnore. Also, Git has Git LFS and you should probably make sure you use that if your repo is large
But both these things apply to everything really, not just Unity
I have get started with it but idk how to publish any changes of my project so my friend can see it and get the changes?
That is an issue with your experience with Git, and it has nothing to do with Unity
I suggest you look up a basic Git tutorial
Also, these type of questions apply to the XY problem. Instead of asking how Unity works with Git, you essentially just want to know how to use Git collaboratively.
So do you have a titourial or something?
{
collider.OverlapCollider(contactFilter, collidedObjects);
foreach(var x in collidedObjects)
{
OnCollided(x.gameObject);
}
}
private void OnCollided(GameObject collidedObject)
{
}
private void OnEnable()
{
interact.action.performed += PerformInteract;
}
private void OnDisable()
{
interact.action.performed -= PerformInteract;
}
private void PerformInteract(InputAction.CallbackContext obj)
{
}
}```
hi, quick question. how can i:
-when i press the E button,
-it checks if the function OnCollided is ran,
-if yes, then PerformInteract.
you can have a boolean that you flip oncollision and then in update check if it's flipped and flip it back/trigger your function
or that's how you'd do it with normal physics events, which you may not be using?
kay ill try
basically you should think of it in 2 stages:
- in update, collect collision data
- on input, check the collision data you collected and do the thing or not
how 2 make TMP editable?
also fun facts:
TextMeshPro is for world space UI, while TextMeshProUGUI is for screen space UI. You're more likely to use TextMeshProUGUI.
TextMeshProUGUI is part of the TMPro namespace. At the top of your file, you should using TMPro;.
To edit the text of a TextMeshProUGUI, you can use the text member.
using TMPro;
public class Healthbar: MonoBehaviour {
[SerializeField] TextMeshProUGUI hpDisplay
public void OnHealthChange() {
hpDisplay.text = Player.health.ToString();
}
}
u didn't understood me. i mean, like field for msgs in discord
what does TMP have to do with discord
what if you use an Input with some text already in it
or i guess no text if it's like discord, since that's just literally an input field
i mean, u click on the object & type text in it
yes
you mean an input field?
yes
you can set the text member
of inputfield
it will fill up the inputfield in advance
i can't understand how 2 make it focusable
All UI elements are focusable by default. If you mean you want to use code to focus on a specific UI element, you may use EventSystem.current.SetSelectedGameObject(...)
you should just be able to click in and type, but if you can't, make sure that your scene has an EventSystem in it
Also make sure that nothing is blocking the element
ok, how 2 add an event system?
Hey I'm not sure exactly how interacting with the hierarchy using a script.
I'm trying to get get a GameObject of something I got from using the "public GameObject [name]" yknow the deal.
uh, How do I get the game object using a name? like I'm using the current level float, convert it to string, and try to use the name.
Apparently the context I'm using is... wrong. And I have no idea whats wrong about it.
Show your code and describe what you're trying to do with it
alr
This is gonna take a while tho
{
if (Input.GetKeyDown(KeyCode.Q))
{
if (ShutOffGui.localScale == new Vector3(0, 0, 0))
{
CanWalk = false;
ShutOffGui.localScale = new Vector3(1080, 555, 0);
GameObject CurrentLevel = LevelPack.GameObject.Find(level.ToString());
Transform wallsTransform = CurrentLevel.transform.Find("Walls");
}
else
{
CanWalk = true;
ShutOffGui.localScale = new Vector3(0, 0, 0);
}
}
}```
'level' is a float, that I just add +1 to it everytime the player touches smth specific.
But the map I'm testing on, doesn't have that, so it doesn't matter.
'Levels' in hierarchy is what I mention as 'LevelPack'
what I'm trying to do is get a system that automatically goes to the next level when touching the specific thing, that I'm not showing in the script right now.
GameObject is a class name, you cannot access it from LevelPack which I presume is a GameObject itself
And Find is a static method, available only from class-level, not instance-level
Well, how DO I get the GameObject I'm trying to get?
because thats the part I've been really annoyied about.
I mostly use ChatGPT to understand stuff, which, yes I actually learn from.
And none of the answers actually gave me something that works
You can either put a new custom component onto Levels, have an array of levels there, and access it via that
the docs tell you that you can use the "/" character to traverse hierarchies, so it's probably going to be fine with something like:
GameObject CurrentLevel = GameObject.Find("Levels/" + level.ToString());
but you should consider an alternative approach, as finding things by name is very error prone and slow
OH. So it's just like files!
(from my expirience on godot, and file explorer)
but try it out @modest dust suggestion, it should be much better
having an actual level component instead of using names
Yeah, but as he says, finding things by name is both error prone and slow
Oh, wait so I could just use tags right?
I'm normalized to doing that from roblox
you could, but not really the best tool for the job
ideally your "Level" game objects should contain a component (Level : MonoBehaviour) that hold the level information
so you can either find them by type or have them referenced directly in the inspector
Custom types and references will always be stronger and more flexible than finding things via name or tag
Huh, Okay I'll go more into researching that kind of stuff
Are you telling me to make levels into files and then load through files?
Same way as you have this custom script, make another one for levels, and the same way you reference LevelPack via inspector (I hope) reference those custom components to access them
I have got alot to learn 💀
all it is is making a new script which is on every level to hold your level information, which then you access like caesar said
I didn't even know scripts could be used like that
public class Level : MonoBehaviour // Put that onto each level
{
public Transform walls; // or some other type
// Some level data
}
public class LevelManager : MonoBehaviour // Put that onto Levels or whatever else
{
public Level[] levels; // Drag each level into this array, or via script if each level is a child of this GameObject
}
// Inside your update
...
Level currentLevel = levelManagerReference.levels[index];
Transform walls = currentLevel.walls;
A simple example
Also I would not recommending learning by GPT as it will give you unreliable answers, I would suggest learning by documentation or these #💻┃unity-talk message
Yeah but the only way to be, not, "the guy who always asks code questions" on chat is really hard, unless I could just spectate on every single question that happens on chats
why is it bad for you to ask questions in a help channel, that would be counterproductive would it not?
I would argue that you ask more questions and let someone answer them, as there is nothing wrong doing so
#archived-unityplay isn't just that, and last time I asked a ton of questions on this chat, I got critized to go into the unity website and learn through there
That's why he recommended to learn via the docs and provided links
There's no issue with asking a lot of questions, but know the basics at least
Alright, but from my perspective I dunno what basics is, And if I do know I guess now I'll at least try to go to the docs to understand that
the basics would be debugging, knowing what variables are, referencing, etc
debugging is a big one
Also after a bit of reading MEANWHILE talking here, from what I'm understanding this is just roblox tables kind of,
which just holds a bunch of whatever value you want, (which on roblox is LITERALLY JUST STRINGS), So if I want to hold values of names I could use strings
yeah... ALOT. of things.
https://dotnet.microsoft.com/en-us/learn/csharp
https://learn.unity.com/pathways
Best if you just get through these two
In the same order as I sent them
Docs aren't really for learning, mostly if you need to search for how something works once you know the basics
I would say they are for learning new things you do not know, as they explain things in an orderly manner
I could try the pathways but if it has mostly videos It's not the best way to learn things from my side
it is videos, but you are suppose to follow along I believe
Try it first, judge later
You're supposed to follow along them and make your own project (fix an existing one) at the end using what you learned
ngl unity should def add a code-babies channel or smth
you are in a beginner channel, I think that would be enough
I think I've actually been here before :O
Would be probably used by those who refuse to learn the basics which are available for free online, linked here, and suggested every 5 minutes
which is, (kind of) me
Then get started and learn
you should be ecstatic to learn the basics
I've left and rejoin this place like 3 times already, because I either gave up and came back or was too annoyied
so I'm kind of more expirienced about asking for help here than actually knowing the code by itself
which probably tells alot
that's not very healthy
about what you already told me 💀
guys help i cant do math
what should my sprite resolution be if i want it to be fullscreen?
do you actually desire to use c# or unity?
my assets are 100 pixels per unit
yeah, I don't wanna stay in "beginner people" place
and more, I will try to improve the habit of going here or going to chatGPT to ask for help
That's why you've been sent the links where you can learn the code by itself, otherwise you'd be asking questions endlessly without knowing what you're actually doing
Going to websites to pretty much read of a book or see someone do stuff is not... fun? I guess?
I mean, coming here is more beneficial than not coming here, the whole purpose of this channel is to help people
Well, I am actually asking why things are the way they are most of the time
but learn the basics as a starting point, they've helped you out already by giving you good resources. even if it's not fun, you're not gonna get anywhere without learning
for example if I got an answer from you about the script after you sent me, like the data stuff
I would've just copied it and kept it in unity
trying to figure it out
No one said learning is always fun, but you gotta do what you gotta do in order to get to the interesting stuff
you learn that by going to those links lol
its like taking a phone and taking it out piece by piece trying to understand it
which is DEFINETLY not healthy
but it can teach like a very very slight bit
even though I could've done x5 better
if you don't know a single thing about any of those components you're going to get nothing out of it
than that very very slight bit
sure you know how to arrange them back in the way they were already arranged previously
but you didn't get anything out of it
it's a difference between understanding and just copying something
No, I'm not like a zombie or, pretty much a robot that keeps data of how others did things only to repeat it when I want it
Check out blogs on the topic https://docs.unity3d.com/Packages/com.unity.2d.pixel-perfect@1.0/manual/index.html
personally I really like that example
Yeah, I took apart like 10 phones for no reason and didn't learn anything from it, go to the linked websites and actually learn something lol
No point arguing about it
i'm glad you like the thing you have come up with, just go to the linked websites
@topaz ice Instead of talking about it you should start learning.
well, I'm in a middle of conversation
trying to get the point right in all perspectives
of whats going on
one that isn't of much use to you, if you'd like to learn go to the places people have introduced to you
It's an off-topic one and full of excuses.
... yeah no I'll just go, we were already done with the conversation
Hi, I'm trying to move objects using the mouse position but I can't find a way to clamp the movement to the camera/screen to avoid clipping, this is what I'm using so far.
Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10f);
Vector3 worldPos = Camera.main.ScreenToWorldPoint (mousePos);
if (bIsBeingDragged)
{
transform.position = worldPos;
}
Can you... use RigidBody or smth so hitboxes actually work?
Personally thats what I do but it sounds like a big stretch
I was going to go that route if I can't get this to work
alright
that most likely will not respect physics if you move your mouse fast enough
I guess thats true
wait
if you use settings right physics won't exactly apply, ut hitboxes still will right?
you can just make the drag settings to 0
and it won't exactly move far away depending on physics itself
...but also I think what you meant is that the mouse can just go through things
I dunno, what ever happens, happens
Also if you ever feel like it you could make a fake mouse, So the player is dependant on the thing that has physics meanwhile the actual mouse isn't visible
I'm not sure what you mean
Well I dunno if were exactly talking about the same thing, but
If you try to move things using .AddForce with RigidBody it can't go through things.
And by making Linear Drag and Augular Drag to 0
It's gonna go perfectly accurate to the mouse
IF we do a bunch of math to set exactly where the mouse is
But I still think its a little over complication, and that we could use some other technique
Kind of janky but got it to work
Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10f);
Vector3 worldPos = Camera.main.ScreenToWorldPoint (mousePos);
if (bIsBeingDragged)
{
if (mousePos.x - objectWidth >= 0 && mousePos.x + objectWidth <= Screen.width && mousePos.y - objectHeight >= 0 && mousePos.y + objectHeight <= Screen.height)
{
transform.position = worldPos;
}
}
how 2 make input field interactable? i mean, i have 3d tmp with component input field but when i click on it - nothing happens
quick question,
protected virtual void start()
when i made an inherited script, i wrote
protected override void start()
question:
-do i need to write base for all of the functions to be inherited or is it by default already is?
-whats the difference if i use the new keyword?
using the new keyword instead of overriding hides the base implementation. and if some object has a reference to the object but stored as the base implementation, if it calls the method that uses the new modifier then it calls only the base implementation because the new one is only available when the object is referenced as its own type.
as for the base keyword, you would use base.start() in the overridden method if you want it to call the base class's start method too. if you do not want that behavior then you do not need to do that, calling a base class's method is really the only use for the base keyword
How do I SetActive all objects within a public GameObject[] group; variable?
Use a foreach loop
I cant figure out how to do it, here is my code, please help
foreach (group Group in group)
{
Group.SetActive(false);
}
what makes you think that is even close to correct?
tell me what to google
no need to google, think.
what is the base type of group?
This is the first time Im working with arrays, I dont know what base types even are
does this tell you nothing?
GameObject[] group;