#💻┃code-beginner
1 messages · Page 593 of 1
oh right, if i dont inherit from monobehaviour though it says it doesn't exist in this context, is it under a specific namespace?
yes its under UnityEngine namespace
im using unity engine but Destroy and Instantiate are both not defined
Nevermind, i needed to do object.instantiate
im stupid, cheers
You can also do UnityEngine.GameObject.Instantiate
Does anyone know how to fix this error?
Why are you writing in notepad?
Please properly share your !code and indicate what UIHandler.cs line 32 is
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
On top of that, take a good few minutes to wonder why you write code in notepad rather than using a proper editor like Visual Studio, Visual Studio Code or Jetbrains Rider. Notepad is not suitable for writng code in the slightest.
I really hope it was just for the picture
This is UIHandler:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class UIHandler : MonoBehaviour
{
private VisualElement m_Healthbar;
public static UIHandler instance { get; private set; }
// UI dialogue window variables
public float displayTime = 4.0f;
private VisualElement m_NonPlayerDialogue;
private float m_TimerDisplay;
// Awake is called when the script instance is being loaded (in this situation, when the game scene loads)
private void Awake()
{
instance = this;
}
// Start is called before the first frame update
private void Start()
{
UIDocument uiDocument = GetComponent<UIDocument>();
m_Healthbar = uiDocument.rootVisualElement.Q<VisualElement>("HealthBar");
SetHealthValue(1.0f);
m_NonPlayerDialogue = uiDocument.rootVisualElement.Q<VisualElement>("NPCDialogue");
m_NonPlayerDialogue.style.display = DisplayStyle.None;
m_TimerDisplay = -1.0f;
}
private void Update()
{
if (m_TimerDisplay > 0)
{
m_TimerDisplay -= Time.deltaTime;
if (m_TimerDisplay < 0)
{
m_NonPlayerDialogue.style.display = DisplayStyle.None;
}
}
}
public void SetHealthValue(float percentage)
{
m_Healthbar.style.width = Length.Percent(100 * percentage);
}
public void DisplayDialogue()
{
m_NonPlayerDialogue.style.display = DisplayStyle.Flex;
m_TimerDisplay = displayTime;
}
}
and this is PopUpSystem:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class PopUpSystem : MonoBehaviour
{
public GameObject popUpBox;
public Animator animator;
public TMP_Text popUpText; // Corrected line
public void PopUp(string text)
{
popUpBox.SetActive(true);
popUpText.text = text; // Set the text for TMP_Text
animator.SetTrigger("pop");
}
}
apologies, I'm learning this for a tight deadline and this is what my school used
General Unity help requires you to have a valid configured !ide to be helped. Perhaps look into downloading Visual Studio and configuring it. The configuration takes only a minute (excluding downloading)
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
That said, what is line 32?
using notepad as code editor is crazy
i believe it is cs m_TimerDisplay = -1.0f;
my bad
m_NonPlayerDialogue.style.display = DisplayStyle.None;
scuffed
gang i just need help with the pop up system 💔
proper IDE would tell you if the line 32 is the one you refers to, anyway your private VisualElement m_NonPlayerDialogue; is just null
this m_NonPlayerDialogue = uiDocument.rootVisualElement.Q<VisualElement>("NPCDialogue"); return null instead of proper VisualElement
my bad, havent cleaned it up from what i was trying earlier
check if you dont mispelled NPCDialogue or if the element exist
It's not okay to post here without using an IDE, as it's a waste of everyone's time--especially your own
and you didnt provide code for the 2nd error
@tardy inlet ,
download Rider https://www.jetbrains.com/rider/
It's free with a personal license and has great Unity integration.
Alright I'll try thay
PopUpSystem pop = GameObject.FindGameObjectWithTag("popUpBox").GetComponent<PopUpSystem>();
you didnt set tag for that GameObject then
Despite the error not being IDE related I still strongly suggest you consider a better IDE
The fact your school even has you write in notepad is absolutely insane
Better? That's not an IDE at all lol
Like writing on a piece of paper
Well yeah, it's not even an IDE. Just get an IDE lol
well it wasnt on paper sheet so its still not that bad
add new tag "popUpBox" and assign it to the GameObject
got it, thanks
also, I'm trying to get an animation to play when I press space bar. The box itself already plays the animation whilst the button and text do not.
@tardy inlet , after you've installed Rider btw,
you'll need to set it as your default script editor in the Unity Preferences (shown here but, you'll want Rider instead of Visual Studio). After that, next time you open a script through Unity, it should open in Rider.
https://unity-connect-prd.storage.googleapis.com/20220608/learn/images/3e91fa0c-1f51-47f0-9c78-dcc3f2911812_image1.png
alr, doing that now
hope thats not a school project which you get as homework and ask us to solve it
Hello, i am new to Unity and Programming as a whole, i would need some help from someone a bit more experienced to set up a project, that i can work on with my school mates, i just cant figure it out😅 . If there is someone willing to help, please DM me, it would be very much appreciated
next time send screenshots and not phone pics of your screen too 😐
Whether it's a task from school, your own game project, or a task at work-
Isn't our job as developers to use whatever resources are out there to find answers to the problems we face? ;)
Start with unity learn: https://learn.unity.com/pathway/unity-essentials
nope its for a club thing
those warning may give you a hint
I'm not that new, i would just need someone to help me set up collaborate or something, the coding i will figure out myself eventually. Tho any help is appreciated, so thank you!
fixed the warnings which were that I named parameters in the enemy animator wrong, still no success with the pop up
This might be helpful
https://www.youtube.com/watch?v=9IvXupmgl88
Get an introduction to version control in Unity, how to set up your own repository, invite collaborators, and check in changes.
Unity Version Control (previously called Plastic SCM) is part of Unity DevOps which provides robust version control and CI/CD solutions in the Unity Cloud, so that you can release more often, catch bugs earlier, try m...
Git has never failed anybody when it comes to collaboration. Combine it with Github and Github Desktop or another GUI application and you can very easily set up collaboration: https://www.youtube.com/watch?v=8Dd7KRpKeaE
🔥 Learn how to build a responsive website from a Figma design with HTML, SCSS, and JS ➡️ https://coder-coder.com/responsive/?utm_source=youtube&utm_campaign=git+github&utm_medium=content
😎 Join the Coder Coder Club and get sneak peeks of videos: https://courses.coder-coder.com/p/club
In this video we'll be going t...
Also look up "Git LFS" for large file support when it comes to Unity.
Just FYI (to help with learning/ searches/ etc) - the product called "Collaborate" does not exist any more (and was crap). "Unity Version Control" (originally known as PlasticSCM) has replaced it. But the majority of people use Git + GitHub/ GitLab
Also please don't use Github Desktop 😅
Citation needed
Github Desktop is fine for beginners/ non-devs
(and more experienced people if that's what they're happy with)
Yeah I can see more complex features being an issue, but it's a very stable and friendly visualizer for committing and pulling changes
Git Fork is something I think Halfspacer also mentioned a while ago which looks like a promising step in terms of GUI solutions
I've mentioned it loads, which I originally found out about because of ... vertx or fogsight suggesting it years ago
I'm a big fan of Fork, but you also have SourceTree
SourceTree is to be avoided though 😄
Piece of shit that it is (or was when I last used it years ago)
me who uses sourcetree every day 😐
Visually it's decent though. (and I agree, switched from SourceTree because performance wise it was garbage).
But my main gripe with Github Desktop is how different it is from most other git clients out there, which makes it difficult for the rest of us to help beginners/non-devs when they run into issues
tried git fork ages ago but had some weird problems that made me ditch it
GHD is super simple though, it's easy enough to work out
Hi, I am a bit confused, ... if he(refers to speaker in the tutorial) had to make a getter and a setter function public for clearCounter why did he just not make the field public? https://youtu.be/AmGSEH7QcDg?t=12457
private ClearCounter clearCounter;
public void SetClearCounter(ClearCounter clearCounter) {
this.clearCounter = clearCounter;
}
public ClearCounter GetClearCounter() {
return clearCounter;
}```
😐 java moment
Its usually to let you change how the value is set or retrieved later alot easier but you should use a property instead.
I would guess he intends to extent on the functionality later, perhaps add some kind of checks or additional functionalities to the getter or setter functions.
I do know that but in this case he is not adding extra steps in reading or writing so wouldn't it just make sense to make the field public?
tbh yes, if there is no good reason at this point i wouldn't bother or just do {get; set;}
that could be a reason, right
Encapsulation. Fields should never be public, they should only be changed by the class they are in.
Those also aren't properties (Getter/ setter), they're public methods
does public Object field; and public Object Field { get; set; } make any difference?
The explicit Get and Set functions also make it easier to spot where you're simply getting the value and where you're setting it.
Is anyone okey with guiding me a bit through? I do have GitHub Desktop installed and a Repository set up, but how to i connect my unity project and make it available to others? Oh and another thing i need to consider, at home i can do and install everything i need, at school most downloads require an Admin verification.
a property makes a get/set method behind the scenes for you. "Auto properties" can be good as you can do stuff like public int myInt {get; private set;}
Because of encapsulation. Making the field public means anything can change it, whereas a method can give you more control over what is returned or set. For example, your method can have additional validation added, which ensures the value is set properly. Generally it's also a lot more clear what modifies the state of your class.
Additionally, the methods can have their own accessibility modified. For example, the get method can be public but the set method can be private. This way you can expose the value to other classes, but these can not set the value. It's that extra bit of clarity.
You can also just make the field public. What gets and sets the value then, though? The state becomes unclear and you can't very it is correct unless you do this each time you access it.
That said, one very good alternatives is properties. These work by basically combining the get and set method into an inline solution and acts as a field, much like the methods. You can specify a getter and a setter, or limit it with just a getter if you are not allowed to set the value (because it's fetched elsewhere).
Fun fact: Properties are just methods in disguise in the end. The convenient part is that you can always be sure the type you get and set match the type of the property.
Yes. One is a field, one is a property. Note a property does not hold a value, but rather C# uses a backing field which you don't see. So technically property Field secretly has a backing field _field where it gets or sets the value. This behaviour can be modified by updating either the get or set method.
This wasn't always the case in C#. A while ago you had to explicitly specify the getter and setter, and even the backing field. It's all syntactic sugar.
so at the end if you don't have any validation for setting or extra steps for reading, making methods for the property just makes it easier to debug and read the code right?
And, like I said, it's just a more convenient way to specify get and set methods
Just making properties is more convenient
It only makes sense if you expose or validate data, though. You can make general private fields that store data, but if you allow other classes to access it you should definitely pur a property in front of it, for example.
Take a look at this: https://sharplab.io/#v2:D4AQTAjAsAUCDMACciDCiDetE8d3CyEADIgGID2FmiA5gKYAuA3IgM5OsC+sXQA=
This is what the code actually does. It's a bit confusing due to the syntax, but notice the code I wrote (left) just unwraps into a bigger property with a "secret" backing field behind it.
got it thanks
this is not #💻┃code-beginner stuff anymore
It doesn't really matter what it is
The point was explaining how a property works
Just the JIT bit is unrelated (removed now)
which is out of scope of their initial query
It's not, this is how a property works and why it's different from a field
convo/ explanation was pretty much over - no point really complaining about it
Well, the explanation was over, which is why the additional technical explanations risk creating confusion.
I understand it though
I'm fine with explaining it more in a thread if you're really interested. I doubt it helps much but understanding the underlying logic (and also how things used to be) is nice as an extra since C# has a lot of special syntax to make things easier
coming from python, C(never used it but I can understand C code) and TS, CS indeed have some extra syntax
You can generally take your code into sharplab and see what it turns decompiled C# into. That's basically the code without any of the extra syntactic sugar as it's called.
okay
or use JetBrains dotPeek to directly view your assembly .dll so you can see the c# code and corresponding IL code
I use VSCode and I like it, I also use it for all the languages I use
its a tool to view assemblies, not IDE
oh nevermind
I chat in the C# Discord a lot and they always recommend LinqPad. Definitely worth a look
gonna check
Good day, I'm new and wanted to try this Unity game developer app any advice,course,path should i do to improve over-time. from the basics
its good tool but serve different purpose, can't view directly the assembly but can reference it and use in queries then view its IL code
with dotPeek i can directly see the assembly as C# and IL code or low-lvl C# also it refresh auto
like so
Tbh I haven't tried Linqpad enough yet to know what it can do
Dotpeek is paid tho
Oh it's free
My bad.
and include inspector view of how those missing in build elements are assigned
and where they are placed in Assets
how to fix error? "Random" and "range"
public class randommusic : MonoBehaviour
{
public AudioSource audioSource;
public AudioClip[] mySounds;
private AudioClip activeSound;
void Update()
{
if (Input.GetKeyUp(KeyCode.M))
{
activeSound = mySounds[Random, Range(0, mySounds.Length)];
audioSource.PlayOneShot(activeSound);
}
}
}
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class PopUpSystem : MonoBehaviour
{
public GameObject popUpBox;
public Animator animator;
public TMP_Text popUpText; // Corrected line
public void PopUp(string text)
{
popUpBox.SetActive(true);
popUpText.text = text; // Set the text for TMP_Text
animator.SetTrigger("pop");
}
}
I've switched my TMP 2D Text to 3D now, and now "Object reference is not set to an instance of the object." The line specifically is
popUpText.text = text; // Set the text for TMP_Text
It's Random.Range Range is a method in the Random class.
activeSound = mySounds[Random.Range(0, mySounds.Length)];
thanks
reassign it..
I think they meant they re-assigned the reference from a TMP 3d text component to a 2D Text one.
Oh no wait
You're right
I've just helped them in #📲┃ui-ux - the UI TMP was deleted, and a 3D TMP created.
There's no code issue here
Same error, now in this script:
https://paste.mod.gg/ydzpxlhbwlky/0
Line exactly is:
PopUpSystem pop = GameObject.FindGameObjectWithTag("popUpBox").GetComponent<PopUpSystem>();
I don't see the issue
A tool for sharing your source code with the world!
so did u tag the object in inspector?
press on this and screnshoot the inspector top bar or whole
yup
u have there the component?
There's only two references on that line that could be null, so if it's not the tagged gameobject, I'm guessing the gameobject is missing the PopUpSystem script?
Other possibility is you've tagged multiple gameobjects with the popUpBox tag, and FindGameObjectWithTag will get the first one it finds.
everything else is untagged too.
If that object is permanently in the scene, then doing Find is pointless (and silly). Expose the reference and assign it
yea stop using a tag its not helping you out...
Woah woah woah. This is a tag-free zone
you should debug it, first target the gameobject and check if its null if its not then the problem is with component itself
anyway keep searching for tag and component for static gameObject looks bad
Great opportunity to try out the debugger in Rider ;)
debug logs all the way
I wish there was some middle ground for debugging update loops
either spam your console, or continuously step through it
Conditional breakpoints 😋
oh yeah true. Effort though
I do need to head off for today but I’ll continue trying tomorrow, thank you for all the help even though i was difficult to work with lol
Does the runtime Scroll View support touch input (scroll on drag) on mobile?
If so how can I activate it?
yes - dont need to do anything special
I would expect mouse controls to translate into touch pretty easily
otherwise just register touch points as pointer events
you need an active event system in the scene
Is there a documentation?
yes
Would you be so kind and point me to it? I´ve been looking for ages how I can do this drag scroll
google -> unity scroll view with touch
some google posts actually a little dated. I actually see people saying to do what I mentioned, but the new input system I believe changed it all up
Yeah that is why I am struggling
so... you're using the new input system?
Yeah
That's rather important information you should have shared with your original question.

Make a basic scroll rect and try that. If that doesnt work then I'm sure it's event system related or controller
or perhaps the scroll view doesnt work with touch scroll still (but I assume that incorporates the scroll rect anyway so idk)
Ill figure something out aight aight
Also try getting it to work with mouse control first if you havent
I have been thinking about why migth it be and... could it be that 2D colliders don't detect collisions from outside their plane? Like this comming from the camera towards the background, so maybe is that?
Or did I just make the biggest made up in history?
2D Colliders? But you are using 3D Raycast here
Yeah, I am, I need the raycast to come from a different plane than the rest of game
I have a question about Collisions for 3D.
I am trying to keep track of all of the objects the player capsule is colliding with (for example, the floor and a wall) by storing the Collision object given in OnCollisionEnter(). However, the length of my Collision list Never goes past 1, without calling OnCollisionExit(), when it should be 2 due to colliding with both the ground and a wall object.
I suspect what is happening is that Unity is using the same Collision object and just changing its values instead of passing a new Collision object. Am I right in this assumption or is this something else?
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics-reuseCollisionCallbacks.html
pretty sure thats the setting
you might wanna just use one of the overlap functions though instead like OverlapCapsuleNonAlloc
potentially, may just dupe the object/grab the data in a custom struct and store it (still, I wouldnt do it this way cause ordering is ambiguous)
So the raycast is supposed to hit a 3D collider?
I mean... pretty sure this is the only case I would need it to be 3D, can I not make it work for 2D?
Make what work? I'm missing a lot of context here
2D game, I want to do a drag and drop over some sprites, and the typical way of doing that is by a raycast to tell what I am hovering over
I could laso kinda just... make an empty collider that follows the map possition to do that I guess...
The reason I wanted to keep track of the colliders it too know if the player is standing on a platform that isn't too steep, meaning that jumping is enabled. Would using something like OverlapCapsuleNonAlloc do this better, or is there another way I am not aware of?
Mmmm...., I guess I could yeah. I was gonna use that to determine the area where it was allowed to be dragged
I think overlap sphere is more common, but yes, doing an overlap check is one of the more common solutions in general.
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics.CapsuleCastNonAlloc.html or https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics.CapsuleCast.html
you can cast downwards, then use the RaycastHit to get the normal
you'll likely be casting downwards anyways if you're manually handling gravity
for a player, you should also manually handle gravity
Raycasting risks missing ledges though, only drawback
Sphere/CapsuleCast also gives a smooth average of the hit normal
Where raycast does obviously not since it's just a single point
i didnt link to the raycast docs even
Hah, indeed you did not. My bad ;)
Why do you need an extra raycast for the normal?
I didn't know it returned the avg hit normal. That's pretty neat
you dont, i wrote RaycastHit which the method gives back
🤦♂️ oops
i feel i wrote that message clearly 😅
I actually like the multiple collider idea
Do we all collectively need a refill on our coffee?
I would just overlap around your character to check all colliders, but use the additional colliders for information
Could doing multiple raycasts in a circular shape around the capsule help mitigate this, or is it computationally expensive to do and not worth the trouble.
the method i linked is literally a capsule cast, its not a line
its as if you moved the capsule in a line
someone make me a 3D collider cast API call so I can stop whining about how box2D has it and not physx API
I might add that you can just use a SphereCast if all you do is cast downwards
Instead of CapsuleCast
CapsuleCast is very useful in custom movement though
Would I want to make the cast just a smidge smaller than the original to not catch anything it is touchning from the side?
Assuming your character is an upwards pointing capsule, that is
i like capsule cast because you can just directly provide the parameters and know that the area covered is your exact capsule. Then any cast distance is how far you want to check for ground. With spherecast you need additional logic, like if your sphere starts in the middle of the capsule it has to move a certain amount to actually leave the capsule
you could, but ideally your player shouldnt be exactly in objects anyways
Good point lol
Should I just stick with the normal SphereCast or the SphereCastNonAlloc? If the non alloc, what would be a good size for the results? I'm not sure how many to expect...
also if your casts start inside an object, it wont detect the object
Notes: CapsuleCast will not detect colliders for which the capsule overlaps the collider
NonAlloc is always better, if this is for the ground you could really just assign like 10 as the array size.
works pretty well right?
Though idk if you really need the non alloc version since you dont specifically need a list. Just the first result
Hello, I'm having a problem with my Audimanager script, I want it to delete one of the "Audio" gameobjects which it does but the audio disappears?
How do I paste my code in here I always forget
when developing for mobile, use the device simulator
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
works even better now xd
the audio will stop if it's on the deleted object, obviously! 😄
Hello, i need to format my TimeDeltatime from "XX,XXX" to "XX:XXX"
i have find that : ToString("0.000").Replace(',', ':');
Its the best way to do that ? i do that in Update() its ok for performance ?
I mean one of the Audios are still there but it doesnt play even tho it is set to play on awake
"Audios" isn't clear on what you mean
Audio source
has it been enabled?
was it enabled earlier than you think and therefore already played it's sound?
using System.Collections.Generic;
using UnityEngine;
public class AudioManager : MonoBehaviour
{
private static AudioManager instance;
void Awake()
{
if (instance != null && instance != this)
{
Destroy(gameObject);
return;
}
instance = this;
DontDestroyOnLoad(gameObject);
}
}
Yes it's enabled
its loop too sorry 😭
its just background music
that code isn't relevant
It's the only one I have on it
all that does is create a singleton of the AudioManager.. nothing else.
It's definitely not managing anything
Yeah and deleting it aint it? It's supposed to make sure only one is in the entire game
it's deleting any gameobjects with this component on..
delete from here and ask in #📱┃mobile - build errors aren't usually code issues.
alright thanks.
Well shit how would I check it then?
Like how would I check if there are more than one of these scripts in the scene
search for a type
t:AudioManager
using System.Collections.Generic;
using UnityEngine;
public class AudioManager : MonoBehaviour
{
int ScriptAmount;
private void Awake()
{
var Scripts = FindObjectsOfType<AudioManager>();
foreach (var obj in Scripts)
{
ScriptAmount++;
}
if(ScriptAmount > 1)
{
Destroy(Scripts[1]);
}
DontDestroyOnLoad(gameObject);
}
}
Like that?
I think it works now 😅
what... how did you get "change the code" from "search for the type" with a screenshot of the hierarchy search..
a needless change ..
how can i access the TargetScene which is outside the static method
note that i cant make a singleton reference to the Bootstrapper since the Initialize will run before Awake
Through an instance of Bootstrapper
i cant
Then you cannot access TargetScene
there has to be some way
No, there isn't.
It's a member of an instance of Bootstrapper
If there is no instance, there is no TargetScene
I cannot tell you what breed my dog is, because I do not have a dog
- Now Awake() and OnEnable() are invoked on MonoBehaviours.
- Then AfterSceneLoad callback is invoked. Here objects of the scene are considered fully loaded and setup. Active objects can be found with FindObjectsByType.```
i can use AfterSceneLoad
issue is you need to offload to an instance sooner to access the serialized variables
or stop using Init on load
yeah now awake will run before the initialize
i can use the AfterSceneLoad instead of BeforeSceneLoad
why not use Awake only then?
what
wasnt the problem you wanted to access instance fields from a static function?
you do you
i cant just use awake
do you know how the RuntimeInitializeOnLoadMethod attribute works?
i do
Hey so I decided to make a first person horror game where you can look around with the mouse and to move around you have to click in the direction you want to go the movement isn't really restricted you can go where ever you want as long as there are walls blocking areas etc. I already have the mouse movement down so how can I implement this feature?
I cant really find anyone talking about it nor videos
So, just normal first person movement, except you hold the mouse button to go forward instead of W?
on mouse click: apply forward motion
Is this object already present and active in the scene before it starts, or is it spawned in?
right im loading this scene again
so it goes awake, then initialize, then awake again
im reading the documentation but im not really understanding
what's the difference between OnTrigger and OnCollision?
i get that i can set something to be a trigger in their collider component but whats the difference between their usage?
One involves interaction with a trigger collider, and the other checks for a solid collider
Triggers do not physically "exist". An object can move through them freely
one bumps into a wall..
one walks thru it.. (say a motion sensor)
AH
both sends a CollisionMessage.. its just how the rigidbody interacts with it
i see
thanks
Actually, only a collider sends a Collision message. Triggers only send "This is the trigger you hit" while a collider has the full collision object, including things like relative velocity, angle, and hit point
@marble hemlock ☝️
one is for overlapping and one is to track hits like if it were a rigidbody
ya sorta.. like here this is a "Toxic Waste Pit"
its a trigger.. my player can walk across the toxic waste.. but once it enters that trigger i start dealing damage
if i wanted to detect when i collided with a wall.. i'd use a Non-Trigger collider.. (so u cant pass thru it)
best of luck
how do i make instances of a gameobject with prefabs? my current code is
void transformCube(GameObject gameObject, Vector2Int location, Vector2Int size, Material material)
{
GameObject go = GameObject.Instantiate(gameObject, new Vector3(location.x, location.y, 0), Quaternion.identity);
go.GetComponent<Transform>().localScale = new Vector3(size.x, 1, size.y);
go.GetComponent<MeshRenderer>().material = material;
}
and i call it with
transformCube(Resources.Load<GameObject>("Prefabs/testCube"), coordinate, new Vector2Int(1, 1), Resources.Load<Material>("Prefabs/Red"));
but it just ends up creating gameobjects with no prefabs like this:
i tried with both a .fbx file and .prefab file and neither worked
bad idea to use gameObject
what's wrong with it and what's the alternatives ?
what is testCube prefab look like
just this
unity already assigns gameObject to a property on the Component
idk if it might be confusing that somehow
That is correct.
this isn't a prefab just a prefab mesh
The main asset is a model prefab.
When you drag testCube into the scene, you get a prefab instance
this?
"Cube" is a Mesh. It's a sub-asset.
the test cube on the right is now a prefab yes
thats where you can attach components on
is there someone who can check my code? I am having a trouble about playerprefs
You've created another prefab, also named "testCube"
🔻
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
Note that the prefab you created does not look like a prefab variant to me
idk what is that mean
its in english bro
read it. posting code instructions
A prefab variant lets you create a prefab that is based off of another prefab.
So you can create your own prefab (call it "Cool Cube", idk) that is based off of another prefab (the one you got by importing "testCube.fbx", producing an asset called "testCube")
so the code is fine its just my prefabs are messed up?
Here is an example.
I created the variant by right-clicking the "Skyscraper" asset and then going to Create > Prefab Variant
you're spawning a model yes, that does nothing but spawn empty gameobject with that mesh
no components
this doesn't make sense
the issue is there is no mesh ;-;
an empty game object can't "have a mesh"
oh i guess it doesnt add the mesh renderer
You have two assets that share the same name of "testCube"
This is not allowed when using Resources.Load
idk I dont spawn that way I use like a sane person fields
ohh i get it
I'm not sure which asset it's finding here
It sounds to me like it's finding your testCube prefab (the one on the right), which has nothing in it
just link the prefab in the inspector as a field and be done with it
Resources is ugly anyway, for a few objects is okay but you start putting everything in that one big file it gets ugly and slow quick for no benefit
how do i add to my script so that i can check if there is a certain script on the game object im currently on
because im currently trying to use my shooting script to check whether the gameobject is an enemy or player
One thing that's a bit odd to me is that there is no prefab sub-asset. Notice how I have a sub-asset like this -- you don't have that in your screenshot
GetComponent or TryGetComponent
oke maybe i should try import it again
how can i do that
If you drag the model prefab into the scene, do you see anything?
im generating a random number of cubes
or is it an empty-looking game object?
make a field [SerializeField] GameObject myThing and drag and drop the prefab there
or make it whatever type you want, ideally you dont really want just "GameObject"
I use Transform is no components on it
yea both versions worked
Ah, that's just because I had "Preserve Hierarchy" enabled
oh i see thank you ill try that too
actually..isn't that the cube, right there?
it's just very small
the mesh is way larger
You just dragged it into the scene.
yea i got the component for enemy
enemy = GetComponent<Enemy>();
now how do i make it so it checks if thats attatched to it?
That is a model prefab.
yup. strings get messy, if you ever change your asset name your whole system is busted. Direct reference in inspector, don't have that issue. Something to keep in mind
ohh oe
The default Blender export settings cause Unity to import things at 1/100th size, so the prefab gets a 100x scale to offset this
If you then set the local scale of your object to a small value, it will become...small!
you want to grab the enemy from the player ?
scale is 100 100 100 its this right?
Correct.
The "natural size" of the mesh winds up being 1cm for every unit in Blender
rather than 1m for every unit
unless your game is like grid/data based... either triggers/collisions or Physics class queries like raycast you then "grab" the collider/gameobject of what you want to check components on then do the thing
ok so i have a shooting script i use for both player and enemies,
In the shooting script i got the component from enemies
and i wanna check if its an enemy, then ill play EnemyShooting()
right now im using a bool to do this but i wanna make it auto check what it is, depending on if it has an enemy script attatched to the game object
im even more confused now i can change the object's prefab in the hierarchy and it works
What does "change the object's prefab in the hierarchy" mean?
through this thing
ah, yes
if i just replace it with the prefab it works perfectly
This completely replaces the object with a prefab
ohh okay
And the prefab has a scale of [100,100,100]
you want the shooting script to alterante between a bool if its enemy or player?
why even bother with the bool then? you make it generic enough where it doesn't matter who its own they both do "Shooting" and Damage to Health
Get rid of the line of code that sets the local scale and you should see cubes appearing properly
I often set up my own prefabs like this:
- Root (has components on it)
- Model (the model prefab)
that way, I can manipulate the model however I want (or even swap it out entirely)
its already alternating between bool if its a player or enemy and plays its respective functions
The player function shoots on holding mouse button 1
and the enemy function shoots when it gets to a vicinity
instead of using a bool i wanna make it check what script it has on it and if its the enemy script, then play the enemy function
I mean GetComponent and check against a Type, but you're just doing the same thing as the bool.. ? why does this shooting script need to distinguish between the two makes no sense to me. it can be generic enough where they both pass their own data on how to shoot
I used to do the same but its redundant. No point on doing
if(enemy)
ShootAsEnemy()
else
ShootAsPlayer()
You can just have Shoot(mydata1, mydata2)
if(hit is health) etc.
Hello
I want to put a delay after a push my key to open a escape menu.
But, when I clicked one time on my key, I can't reclose my UI because delayToActiveState stay true. I don't understand why ?
My script is on a GameManager and not on a script that be potentially disable
using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
public class EchapButtons : MonoBehaviour
{
private InputAction escapeAction;
private float escapeValue;
[SerializeField] private GameObject optionsMenu;
[SerializeField] private GameObject UIMenu;
private bool isOptionsMenuOpen = false;
private bool delayToActiveState = false;
private void Start()
{
escapeAction = InputSystem.actions.FindAction("Echap");
}
private void Update()
{
escapeValue = escapeAction.ReadValue<float>();
if (escapeValue == 1f && !delayToActiveState)
{
Debug.Log("EchapButtons pressed");
if (isOptionsMenuOpen)
{
StartCoroutine(DelayToActiveState());
Time.timeScale = 1;
optionsMenu.SetActive(false);
isOptionsMenuOpen = false;
PlayerVisionController.instance.SetVisionActive(true);
}
else
{
StartCoroutine(DelayToActiveState());
Time.timeScale = 0;
optionsMenu.SetActive(true);
isOptionsMenuOpen = true;
PlayerVisionController.instance.SetVisionActive(false);
}
}
}
private IEnumerator DelayToActiveState()
{
delayToActiveState = true;
yield return new WaitForSeconds(0.5f);
delayToActiveState = false;
}
that yield dont work when timescale is 0
well
if you use WaitForSecondsRealtime it works fine
not if the gameobject is disabled ofc*
Indeed. It takes an infinite amount of time for 0.5 seconds to pass in-game (:
Nice it works
Thanks 👍
btw what makes enemy function so different than player ?
don't they both do Damage to a Health component ?
because player shooting requires input, while enemy is auto within a range
they both have input if you think about it
yea ikwym but im shit at coding so idk what else to do
send your current class
this way also know how you plan on grabbing the other to do damage
my damage is not even on the shooting script, i put it in playerbullet script because i havent made a damage system for hurting players yet
its like doing a Move method
If you have
Move(){
moveInputs = GetAxis
rb.velocity = moveInputs * speed;```
now you're locked into a move method that only works with Get player moveinputs ??
instead you can make it take any Vector2..
```cs
Move(Vector2 moveInputs ){
rb.velocity = moveInputs * speed;```
and your enemy, bot, or even simple moving objects passes its own v2 as auto
i see
i probably just did it very ineffectively cus i copied and pasted some code from playershoot() to make my enemy shooting
send the script, they can probably be made more modular so you dont even need to bother doing bool thing or component check which is essentially the same thing..
i did the component check thingy now, i did if (enemy== null) {playerinputs()}
{
shotCounter -= Time.deltaTime;
if (Input.GetButtonDown("Fire1"))
{
if (shotCounter <= 0)
{
Shoot();
shotCounter = shootingCooldown;
}
}
//Holding down Left Mouse Button
if (Input.GetButton("Fire1"))
{
if (shotCounter <= 0)
{
Shoot();
shotCounter = shootingCooldown;
}
}
}
void EnemyShoot()
{
shotCounter -= Time.deltaTime;
if (shotCounter <= 0)
{
Shoot();
shotCounter = shootingCooldown;
}
} ```
yeah.. basically you wrote the same thing 3 times
how would I have made it more efficient,
do i put shotCounter -= Time.deltaTime;
if (shotCounter <= 0)
{
Shoot();
shotCounter = shootingCooldown;
all in another function and just call it?
with a few bools you can make this modular
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
void HandleShooting(bool shouldShoot)
{
shotCounter -= Time.deltaTime;
if (shouldShoot && shotCounter <= 0)
{
Shoot();
shotCounter = shootingCooldown;
}
}```
bool isFiring = Input.GetButtonDown("Fire1") || Input.GetButton("Fire1");
shootingScript.HandleShooting(isFiring);
in enemy
bool aiWantsToShoot = true; // some condition you set on your own shootingScript.HandleShooting(aiWantsToShoot);
What do I do ?
I tried making a first person camera but for some weird reason it won't look left and right
are we supposed use crystal balls and this video alone to tell anyhing thats going on ?
use a bit of common sense
see #854851968446365696 for what to include when asking for help
Ok I will post a screenshot of my code here
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
make sure the particle system isn't being instantiated as a child of hte object being destroyed
Well sorry im just trying to attach the code with pastemodgg
But no, the particle system isnt a child, for some reason the projectale doesnt get deleted for the duration the the explosion is supposed to last and the explosion itself isnt deleted at all(Which i am guessing is something i messed up with references)
here is the code
https://paste.mod.gg/basic/viewer/afhboevthshd/0
A tool for sharing your source code with the world!
so for starters, you should use ParticleSystem as the type for your prefab reference, then you won't need to instantiate as a GameObject only to turn around and GetComponent, Instantiate would return the ParticleSystem on the instantiated object so you'd just then call Play and Destroy.
however, the only way the object with this component on it would not be destroyed is if there were some exception being thrown before Destroy is called in OnCollisionEnter2D
oh and when using paste.mod.gg you don't need to (and shouldn't) click that Basic button before copying the link because that shares it without syntax highlighting. just click save and copy the link in your browser
` using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[Header("Movement Settings")]
public float moveSpeed = 6f;
public float jumpForce = 8f;
public float gravity = 20f;
public float airControl = 0.3f;
public float friction = 6f;
public float maxSpeed = 15f;
private CharacterController controller;
private Vector3 velocity;
private bool isGrounded;
private void Start()
{
controller = GetComponent<CharacterController>();
}
private void Update()
{
HandleMovement();
ApplyGravity();
controller.Move(velocity * Time.deltaTime);
}
void HandleMovement()
{
isGrounded = controller.isGrounded;
Vector3 input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized;
Vector3 moveDirection = transform.TransformDirection(input);
if (isGrounded)
{
velocity = moveDirection * moveSpeed;
if (Input.GetButtonDown("Jump"))
velocity.y = jumpForce;
ApplyFriction();
}
else
{
AirControl(moveDirection);
}
}
void ApplyGravity()
{
if (!isGrounded)
velocity.y -= gravity * Time.deltaTime;
}
void ApplyFriction()
{
if (velocity.magnitude > 0)
velocity *= (1 - friction * Time.deltaTime);
}
void AirControl(Vector3 moveDirection)
{
velocity += moveDirection * airControl;
velocity = Vector3.ClampMagnitude(velocity, maxSpeed);
}
} `
that doesn't mean you should paste the entire thing into discord..
Thank you boxfriend, i'll come back in a minute with the new version
Alright now i think im encountering the problem you mentioned earlier with the ps being a child of the gameobject, how do i avoid that tho
https://paste.mod.gg/lhzegxpqfgcs/0
A tool for sharing your source code with the world!
you've changed the parameters for the Instantiate call, you are now using the overload that specifies a parent object instead of the one that specifies a position and rotation without a parent
Thank you made, now it works perfectly, you are absolutely fantastic
Actually no, it doesn't work as well as i thought, i think the class is destroyed before the timer for the ps destroy is finished so none of the ps instances is actually destroyed. Do you have any recomendations how i can separate them
that's not how that works
nope my bad
i was destorying the ps component and not it's game object
that's why the scene was filled with empty objects
Still, thanks a lot mate
guys! question, what causes this type mismatch error? this is my script
using UnityEngine;
using UnityEngine.UI;
public class KillCollider : MonoBehaviour
{
private Counter sphere;
[SerializeField] GameObject sph;
public Text CounterText;
private void Start() {
sph = GameObject.Find("Box");
sphere = sph.GetComponent<Counter>();
}
private void OnCollisionEnter(Collision collision) {
Destroy(gameObject);
sphere.count--;
CounterText.text = "Score: " + sphere.count--;
}
}
i really dont know why this happens, and it happens quite often, my main theory was because i had it assigned somewhere else but i think thats hard to be true
you're either trying to drag an object that has no Text component on it or you are trying to drag a scene object into a prefab
That usually happens when you change the type in code after assigning a previous object. Imagine it was typeof(GameObject) and now its text but you dragged the Gameobject first. You have to reassign it when you change the type in your class
@compact stag forgot to tag
yeah, so, it is a prefab
dragging a scene object into a prefab doesnt work? why is that?
assets like prefabs cannot reference scene objects because while the assets always exist, the scenes are not always loaded
Because prefab is just a blueprint of something you can copy into runtime
pass the reference at runtime when you instantiate the prefab https://unity.huh.how/references/prefabs-referencing-components
oh! alright, thank you
thank you guys!!
this is a code channel
is it better to make a custom friction system or just settle down with unity's physics system?
So much information missing. Depends on your situation. What speaks against the physics system? What is your goal?
for me, the friction aka. "angular damping" as unity calls it is very slippery and im thinking about making my own one to not use some ridiculous values for speed and damping
If you dont need the rest of the system or can work within that and expand, why not. I mean you just answered your own question. Either you are using it wrong or its not working for your situation.
fair enough
Unity calls friction "friction". Angular damping is something else.
So if you've been trying to add friction with angular damping then that explains why it doesn't feel right
friction is applied when objects are touching each other; linear and angular damping cause a rigidbody to constantly lose linear or angular velocity
Hey! I'm having an issue with Visual Studio as a beginner. I'm starting my first project, and when I write code like gameObject, it doesn't show any color or suggestions. Like when I type Game... nothing more appears. I tried all of this https://learn.microsoft.com/en-us/visualstudio/gamedev/unity/get-started/getting-started-with-visual-studio-tools-for-unity?pivots=windows but still nothing
(maybe it doesnt matter but : the visual studio editor in package manager shows an lock)
whad
read the page
I only need the 2d and 3d core right?
huh?
yes
ok thanks
also you should keep VS in english if you ever have errors or issues much easier to get help
typically you would refer to a workload using its title, not two random bits of info in its description
oook think I'll change
i dont understand high englisch
wait chatgpt help
use a translator if you do not understand english. but understanding that referring to something by random bits of its description is illogical should be common sense
oh my gawd i understand
yes that makes sense
thanks
do you guys ever made some games?
nope, i use unity as a screensaver
I use unity to do my dishes
anyone know how you would go about scripting spacing between multiple companion AI's that would follow you around
jesus christ, please finish a thought before sending the message
I will write correctly now.
r u using navigation agents?
have a chain-gang..
first AI -> target is player
second AI -> target is first AI
etc
should work right out of the box w/ the appropriate Stopping Distances
I dont think so
what are you using
I installed everything new, followed the steps and it's still not working
if only that page had a list of steps you could take if you were experiencing issues
i guess since you didn't read it you'll never know 🤷♂️
I just wrote some code that has them follow the player and it works fine but they overlap with each other and I dont want that
oh
just tell it to stop if it's close enough
well i would make them collide with each other first
but if u want more than that they will have to check for other agents and make sure they are not too close
and if so move away
vector.distance between the companion and the player. if the companion is close enough then just stop the movement code
its not the player its each other
would I use nav mesh agents to accomplish this?
unless u want pathfinding no
collision is the easy solution
having the script also maintain distances between them is slightly harder but not too hard
just a trigger that adds/removes nearby ones to a list and then it adds velocity based on the closeness or something
I dont necessarily care if they collide into each other per se but like when I stop moving I want them to spread out instead of being in one clump, so would the trigger with the list work best for that
pretty much any formations type algorithm will probably help you out, iterate and spread em
thats one of the most common problems for AI crowds..
best of luck
Ai Grouping.. Spacing.. etc
its not really a code-beginner issue tbh
Learn how to create groups of NPCs that move in various formations in Unity 2022.3. This is the second episode to the AI Mastery series, make sure to follow the first tutorial because we build upon what we made in that video.
Watch the Game AI Mastery Course playlist here:
https://www.youtube.com/watch?v=1VWpFk7wEEM&list=PLMNkk-YfpOgOkNiCuFr3TU...
theres a lot of ways to go about it and it highly depends on the behaviour u want
just start going down the rabbit hole 🐰
hey guys, sorry for interrupting. But should i follow the "Create Dark Souls in Unity" series? i'm a beginer in unity but not coding.
if thats the type of game you're wanting to make then sure..
idk if you guys ever heard of this series
I would start with Essentials and then Programmer pathway
whether u succeed or fail.. its gonna expose u to the things u need to learn about for that genre
mostly for learning
as long as the tutorial is up to date
and not really bad
idk anything about it
ive never watched it and I would assume most ppl haven't so its really just
is it gonna teach u what u wanna learn
following tutorials can be good for learning, giving you tools for when you go and make your own game
@rocky canyon @rich adder thanks for the heads up
dont sleep on the Unity learn site it has really good content
i won't
unity youtube channel also been resuming posting good tutorials for their new packages
I think a lot of people use tutorials to fasttrack their way into the features they want and while that's fine you really want to be learning how to make any feature not just the ones people make tutorials for
it wooorks : D thank you for everything
but i checked a few days ago and it had an error
ill do the dark souls series until its up again
you mean the Essentials ?
yeah
cause the link changed and they havent redirected it yet
or am i in the wrong place perhaps
do you know where can i get it tho?
guess those programmers need to "learn" how to make a link work properly
its working for me
same
try clicking to "explore our learning pathways" and click it again
same problem
try clearing browser cache
thanks
for learning i recommend going thru this as a crash course.. to get exposure to things you'll build upon the farther in ur journey you go
really helped me out at the start
towards the end when he starts building a game u can continue thru that or branch off to ur genre
and always keep Google and the Unity Docs bookmarked
8 years old tho, Do you think thats gonna be a problem?
I was recently following a tutorial on writing a lit shader from scratch
The tutorial appears to have been created for Unity...4 or 5
Worked great
most likely the only problems you'll run into are things being deprecated, but the error messages for those tell you what to use instead
alternatively, you could just use the same unity version used in the course then just transfer that knowledge to newer versions after completing the course
no.. he basically covers the fundamentals.. (in an abstract way at first)
theres nothing really that has changed since then..
even w/ older (specific) type tutorials.. most of those can be followed too..
there may be some UI changes.. (menus in different places)..
but as for the code and functions.. they tend to stay the same..
and if you end up using a function thats outdated.. the IDE will tell you its Deprecated and offer you alternatives..
but thats rare..
just stay away from tutorials that use Javascript lol
alrighty
javascript, you mean
or Monoscript.. if its in c# u good lol
Question isn't there a console tab anymore? Can't add it
yesh.. thats what i meant lol
you can open it from the Window menu up top
i'm gonna use the playlist as a starter
thanks for having my back
then i'm gonna go to essentials
then i'm going to do my own thing
or atleast try
thanks for the tips
if you find a unity tutorial written in Java, you have discovered some kind of evil wizard
lol.. facts
the first few episodes are the most important ones imo
c# structure.. how to add code to ur gameobjects, etc
thanks thanks I tried to add it at the right mid not on the windows tab lol
can you even code in java on unity?
Well..
c# is pretty much java
mmhmm
That would make sense for writing glue code
yeah it supports java in the same way it supports c++, as native plugins (but only for android in the case of java)
the only code ive ever heard of being used with unity is Python..
and thats b/c of machine learning
i'm kind of new to programming languages cus i always programmed in built-in languages on engines like gd-script and gml
i remember seeing a package that lets you write editor tools in Python for some reason
but yeah -- Unity is all about C#
Pretty damn good choice
pythony languages pretty ugly
if you've used gd-script then u shouldn't have much of a problem transitioning into c# and unity
that's finally being deprecated in 6.1 (or maybe after)
i kinda already started the dark souls series
i got to ep 10
who says u can't do more than one?
- lol
but are you *learning * or just copying and pasting someone's code
flexin dat gpu
tbh i always have atleast 3..
no flex or anything
and i've yet to have a processing problem..
and it was like: gd script you make eggs.
c# you make the fire, the pan and THEN you make the eggs
as long as there's only 1 that im actively working on the other instances doesn't seem to hurt anything
copying and asking chatgpt what each thing do
LOL
uh oh
was that a bad idea
if u have half a brain.. you'll be fine using it to talk-out concepts.. and learning and exposing urself to new ideas and features
sadly next gen gonna be so "AI" bound they will have 0 critical thinking abilities
next gen? lol...
well thats good, no competition
heck ya 💪
ok
no chatgpt/AI bots as a resource
i do need a replacement
is there any kind of document?
like the godot one
that helped me a bunch
!docs
theres always mixed opinions.. I say AI is a really good tool..
just don't blindly let it do all the work for you..
and if you do.. don't expect help here.. you'll get shut down quick once someone realizes its AI code..
and we're all getting pretty good at that 😉
so much information in these its actually pretty wild
good to bounce conversations with nothing much more
^ brainstorming ++
(delete AI comments, nobody will know that its AI code then)
until you doesnt know what it does, then you are busted
lol.. it has tells
trust.. lol
Let's delve into the intricacies of AI-generated code!
i was using it to answer some questions, not write code
[very loud explosion sound]
in like "what does private void do in unity?" or sum
yeah but you don't 100% know if what its telling you its true
it tries to prioritize appeasing your keywords rather than giving you correct knowledge
yeah, using the documents is more of a smart move than asking an AI bot that just spit mixed info lol
Unity tried to tie AI with their own Docs and it was pretty miserable
nothing can replace your own experience and knowledge gained
100% agree...
you learn sooo much more from trials and errors
ML training can to but the data its trained on isnt verified or accurate
that was where i learned the most in godot
when i tried to do my own thing
and failing
then fixing
then failing
then fixing
ahh, the Rinse and Repeat of game-dev
you're forgetting the table flip tho
(╯°□°)╯︵ ┻━┻
all good until you dont wipeout 4k hours project
you have to break through that just by expanding your knowledge on other things and take a break let problem marinate
I'm not really sure how I'd tell someone to start learning Unity
I picked it up after a solid 8 years of general programming
most of it was like a roller coaster tbh
i came from Art background.. wasn't that hard tbh
i found that trying to make Exactly what i wanted to make was my best recipe
"im the worst, i'm never fixing this" to "yep, im the best programmer there is"
!docs
https://github.com/SpawnCampGames/Resources/blob/main/101/readme.md
heres a github page i made a while back.. it has links to the Unity Manuals/Docs/ its Youtube channel
a few tutorial series.. and my favorite GameAssets page.. might be something u could benefit from
b/c its Legacy Doodoo
use TextMeshPro
will definitely check it out
idk but you should not
alr ill go to bed, @rocky canyon @rich adder thanks again. I'm genuinely grateful
i won't dw 😂
nah
everytime i hear someone talk abt javascript is always something bad
learning the keywords is pretty easy comparatively
the hard part is syntax and problem solving
javascript has nothing to do with java, strangely
really?
no way
what are they really
yep
ya, two different scripting langauges
its not like script of java?
are both of them a language?
a javascript
javascript is used mainly for web-dev
javascript is a scripting language named after java for literally no reason
well
no GOOD reason
the only thing they share is like
c-like syntax and a name
they are totally different types of languages
made by (I think) totally different people
heres a probably more accurate answer
iirc the name was chosen because Java was hip and trendy at the time
but yeah they have about as much in common as c# and python
errr well idk
pythons syntax is different
Oracle owns Javascript technically
the proper name is ECMAScript
the biggest thing they have in common is that they both suck and should be avoided whenever possible
in favor of better options
at least, that's the name of the standard
honestly both of them are fine but have better alternatives... people hate javascript because of its type weirdness but I didn't mind using it for simple web stuff
you dont have other options for in-browser scripting tho
JS is pretty much the way until webassembly gets standard
typescript is an option ive been told
if you enjoy c# and type-safety at least use typescript
There's also flutter or whatever it's called
then everyone use as any type
what
ive never used it
but that sounds like user error
you also can make web games in unity without typing a single line of javascript! so theres that
it solve errors
Typescript lets you gradually adopt proper static types
dont ask me how that works
https://youtu.be/7_Sdzum4Q3Q?t=11195
Can someone tell me how can this be made. how can i manage blocks in the grid like in the video. I am trying to create a grid and make them fall in it and then snap to the position. But it isn't working well. Can someone help me with what i should be doing here.
New York Mysteries Secrets of the Mafia no commentary -- Watch live at https://www.twitch.tv/haederbazooka
you start out with a giant mess of "any" and then gradually introduce actual types
until there its error and you back to use any
- what is your approach
- what is your problem
i mean
if you have zero interest in writing working code, then yes, you can do the obviously wrong thing
if you want an overview thats fine, but if you are running into issues we can't guarantee our ideas would work for u either
looks like bit of gravity or downwards force.. + it lerps left or right depending on which is closer..
not sure how the rest of it works.. lol its def more complex than it looks
ya, ths what i meant by the lerping part.. it instantly starts lerping left or right as it falls.. so that way when it gets to teh destination and snaps its not so abrupt
which is probably non-trivial
def not a "code beginner" project if u want those exact features
my grad school's data structures class used Tetris as one of the homework assignments
you basically have to make tetris ya
just unity physics and colliders wont cut it
not if you want something consistent
its def just tetris at heart
all the features and mechanics of tetris are at play there
with mouse control rather than keyboard control
tetris + inventory management 😉
resident evil
It seems to have no physics at all, it's just interpolating between the point before a move was taken and after
they fall
it just happens to be that the position after is down
if that counts
Yeah, I would absolutely not want to try to smash this together with actual physics
the grid is the real star 😉
"physics on a grid"
You want to be able to ask "can this piece fit into this space?"
the rest naturally comes from that, really
nightmare fuel
simple really (/j)
This is what I don't understand. Utilizing AI with their docs makes sense. This would avoid looking through tons of pages to find the right document or term. It's a closed loop of their own code; I'm shocked it turned out poorly . . .
Hey! I was just trying to create a grid and snap the position of the block to it and then apply gravity to make it fall. But it wasn't working. So i used chatgpt and now i m totally lost. Can you please tell me like an approach for how should i be doing this. Idk what should i do tbh.
can you be more specific than "not working"
but again as others said you probably dont want to be using rigidbody physics
u were on the right track..
Yeah you would think so, I was basically giving somehow worse results than gpt did at the time.. Maybe it has improved but I haven't touched it since a year or so they made it pretty much paid / so I didn't bother trying again. Apparently now you can drop items fields in the chatbot like normal inspector and you can ask it to do stuff with it, something along those lines
Physics colliders are useful when you can't easily decide "is X interacting with Y?"
grid creation
piece movement
piece placement
If you're on a grid, you probably don't have that problem
my guess is that looking at the docs isn't enough for an AI and gpt has way more data in general
LLMs require an absolutely catastrophic amount of data, yes
(that's the secret sauce)
idk what they fed it or how it works but I feel like data + time is king
that's also why we've...run out of data
nothing else is really worth much
at most they can feed it Disussions.unity.com but nothing gpt doesnt have either
soon XLLMs
By not working is like the blocks weren't snapping right to the position in the grid. They would just snap in between the grids like on the boundaries of the cells.
finally
wrong answers, at scale
cant wait to clock in at the data collection pod every morning
possibly could have fixed that w/ offsets..
well, that's unfair: that's what you'd get if you trained it on Stack Exchange comments
or american size
"Extra Large Big Ass Language Model"
ur piece was probably snapping to the Intersection of grid lines.. and not the spaces between them
Yeah probably
gpt has also seen every reddit post and tutorial and article about unity and every single other post and tutorial about every single other engine and language and api and...
I will check it
also interesting that LLMs cant figure out if a yt video is suitable for advertising and everyone has to self-censor words that are harmless when taken in context.
Remember that you need to unalive the child process
i smell a fast food meme here
XLLM <-- actually looks like a superbowl
1040 😉.. my GPU is a MMLXXX-TI >8)
more like 5090Ti
Can you tell me how should I making those blocks stop falling? Currently i am using colliders and rigidbodies for their movement. I m turning on and off their "isTrigger" option and "gravity scale". And to stop them from falling down i am using an edge collider at the bottom of the scene so that they don't fall
they should use their Grid Coordinates to stop moving..
if(pieceWasPlaced && cantFallAnyFarther){snap to nearest grid coordinate}
not totally sure how u'd do the detection of other pieces tho..
msot likely checking if that coord is occupied by a section of another piece?
also fun, openAI beat microsoft at the worst poduct naming olympiad
microsoft 365 (good luck)
I see i see i will try this 😔 hopefully i don't end up quitting this time again.
o3-mini
i'll see if i can't find some specifics on how its actually done
that sounds like an AWS tier
I would define each piece as a list of positions
^ so im on the right track i guess
You can write methods that check if a piece fits onto the game board
either by checking all of the other pieces, or by just having a 2D array of bools for occupancy
in the latter case, you'd write methods to tag a bunch of positions as filled/empty
(based on the position and shape of a piece)
snapping and downwards movement would be the first thing i tackled.. and once thats sorted the rest would be the home-stretch
Ok so.... it was the 2D collider that I mentioned this afternoon. It works with a 3d collider, but.... now the transform is making the Z axis be literally on top of the camera? Is that transform relative to the camera somehow?
I want it to be like the actual world Z 0 axis no matter where the camera is
How do I tell it that?
I read these and I am always left with more questions than answers....
I guess I could pass it the distance of the Raycast to detect the object
I don't need the plane
transform.position = new Vector3(mouseWorldPosition.x, mouseWorldPosition.y, DesiredZPosition);
after the screen to world conversion just set the position of it's Z manually..
or whatever axis ur working with..
That wouldn't work in a perspective camera though
ah tru.. i use raycast for perspective.. i thought he was refering to a 2d project tho. mb
Who knows, might be
waiting for confirmation 🙂 lol
I'm sure they can figure it out, they have been given loads of options
always helps to debug the values if ur learning ur way around the ScreenToWorld or WorldToScreen stuff..
really helps validating yourself to see whats getting outputted before doing anything extra with it..
maybe not this much tho.. rofl
I eneded up just doing this
yup, thats fine too. (keeping it where it already is on the Z)
[SerializeField] private contentType[] spawningElement; //in type
private Dictionary<GameObject,contentType> allGameObjects = new();
int count = 0;
foreach (KeyValuePair<GameObject, contentType> element in allGameObjects)
{
if (spawningElement[count] == contentType.Subtitle)
{
count++;
continue;
}
if (element.Value == spawningElement[count])
{
RebuildContent();
}
count++;
}```
u think it can be more neat?
if that is the entirety of the loop then you can just remove the first if statement entirely
wait nevermind, ignore that. it doesn't take into account that both if statements can be true
you could make it slightly less repetitive by incrementing count at the start of the loop (you'd need to start it at -1 instead of 0 to keep the same logic), then your first if statement only needs to continue instead of incrementing then continuing
what is the actual purpose of this anyway? it seems like you are relying on the dictionary's elements to be ordered in the same way as your array, but if that were the case it would be pure coincidence because dictionaries do not have a guaranteed order
the script i was doing is a base system of all dialogs and large sums of UI that will use in future, it controls all the elements inside the UI , text, input fields , pics all sorts of thing
right now, the script acts as a spawner for elements inside the UI
its fairly simple, there will be an enum
public enum contentType
{
Text,
Password,
Account,
InputField,
Phone
}```
u populate the enum array and tell the UI which element to spawn
then it will spawn the element from top to bottom
public void RebuildContent()
{
foreach (GameObject element in allGameObjects.Keys)
{
if (element == null)
{
continue;
}
DestroyImmediate(element.gameObject);
}
allGameObjects.Clear();
if (hasSubTitle)
{
GameObject spawnedObj = Instantiate(prefabs[0], transform);
allGameObjects.Add(spawnedObj);
}
foreach (contentType element in spawningElement)
{
GameObject spawnedObj = Instantiate(prefabs[(int)element], transform);
allGameObjects.Add(spawnedObj,element);
}
}```
right now, i can guarantee the sequence because the dictionary is populated one by one based on the enum array
that still does not guarantee the dictionary's order. it is not ordered in a specific way. just because you add the elements in a specific order does not mean they are ordered that way in the dictionary
this whole setup has me confused tbh. why are you using gameobjects as keys to the dictionary to get an enum?
where does that even get populated?
How do you get the code blocks in discord
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
don't the newer .NET actually order dictionaries?
i tried not to question it too hard lol and glossed over it
‘’’cs
//test
‘’’
there is an OrderedDictionary type, but Dictionary is not ordered
That didn’t work
lemme modify it a bit lol
` not ‘
that's because those characters were not `
ohhh that makes sense
im trying to think when i just wouldnt use a List instead i've not ran into a reason to consider dictionaries yet tbh
Okay, so I am able to move the dragged item inside the area that I want it to move in, but I got 2 issues. 1 that moving the cursor way too fast, let's the item object behind since it didn't got time to update to the boundaries of the allowed area within that single frame. And 2, if I am to move the cursor outside the drag area while holding the item and then move inside again, it would inmediatly snap from the previous position to the new one
I would want to make it so if I am outside the draggeable area, the object just moves as close a possible to the cursor within the draggeable area. How could I achieve that?
show your current code so we can see how you are accomplishing this
How can I get the closest point within a boundary to a another point?
That would pretty much solve it
I remember having something for that, but not sure what was the method....
Oka, got that
when my blorb bird falls past y level -15 the game over sfx stops playing.
LogicScript:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class LogicScript : MonoBehaviour
{
public int playerScore;
public Text scoreText;
public GameObject gameOverScreen;
private bool gameIsOver = true;
public AudioSource wingFlapSFX;
public AudioSource gameOverSFX;
[ContextMenu("Increase Score")]
public void addScore(int scoreToAdd)
{
if (gameIsOver == true)
{
playerScore = playerScore + scoreToAdd;
scoreText.text = playerScore.ToString();
}
}
public void restartGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
public void gameOver()
{
gameOverScreen.SetActive(true);
gameIsOver = false;
gameOverSFX.Play();
}
}
BirdScript:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BirdScript : MonoBehaviour
{
public Rigidbody2D myRigidbody;
public float flapStrength;
public LogicScript logic;
public bool birdIsAlive = true;
// Start is called before the first frame update
void Start()
{
logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicScript>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && birdIsAlive)
{
myRigidbody.velocity = Vector2.up * flapStrength;
logic.wingFlapSFX.Play();
}
if (transform.position.y > 15 || transform.position.y < -15)
{
logic.gameOver();
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
logic.gameOver();
birdIsAlive = false;
}
}
its because you're calling gameover every frame
Play keeps starting over the sound
if (birdIsAlive && (transform.position.y > 15 || transform.position.y < -15))
{
logic.gameOver();
birdIsAlive = false;
}```
I cannot combine like a bunch of simple-shaped colliders into one single collider component, right? I would have to a custom mesh for it, correct?
You can have multiple collider components on a single object
you're using 2d, right? that has the composite collider component
I kinda had to make colliders 3d so they would dettect Raycast from the camera...
that is not necessary in the slightest. you can use a physics raycaster 2d instead of the physics raycaster on the camera
assuming you are referring to event system raycasting. if you are raycasting yourself then you're just using the wrong physics class
Like... the camera would send a raycast from the Z-Y plane towards the X-Y plane and am not sure how to handle those connecting
From the camera through the cursor towards a world point in the plane (at Z=0, which is basically where the whole game is)
i asked how
What do you mean how? A Raycast from the camera towards whenever the cursor is
What else can I say?
i dunno, maybe show some fucking code because we are in the code channel and i asked how you accomplished something you are apparently doing in code?
but the answer is the one i already gave and that is you are using the incorrect physics class, you should be raycasting using Physics2D with 2d colliders
and if you're just casting a ray directly into the z axis from an orthographic camera then you don't even need a raycast, you can use an overlappoint
ah yes, i should just assume that this is related to something you asked about 4 hours ago and then go and find that myself instead of you just sharing the code when requested. how silly of me
No, you should not, but you should not get mad either
anyway, i already gave you the answer so we're done here
So... basically does the same but works only with 2D... Why do we have two versions of that again?
2d physics and 3d physics are entirely separate. 3d physics uses PhysX, 2d uses Box2D. they are completely different physics engines so they need to be interacted with separately
I still find hard to assimilate that Raycast are actually part of the physics
So... do I send a 2D Raycast from the camera through the cursor or it's better to use overlaping point?
raycasts are physics queries, they are spatial lookup methods built into the related physics engine to query the current physics scene for colliders in specific areas. that is all they do so they must be heavily tied to the physics engine
and an overlap point is sufficient if you just want to get what the cursor is over. use a raycast if you need to check in a specific direction
But overlaping point would only work if the camera is especifically ortographic, right? Since it returns basically the same result than sending a perpendicular raycast
pretty much, yes. although it probably does work with a perspective camera too because 2d physics is still only in the XY plane
Kk, thxs
Just use raycast, not overlap. It's much more reliable for what you're trying to do assuming your box2d colliders are accurate
So I could use 2D colliders now, and... I use composite to combine them?
It's much more reliable for what you're trying to do
citation needed.
if they are just checking what the cursor is on top of they do not need a direction to check, so a raycast is unnecessary
Are you one of those people that split hairs over 0.0000002 ms?
at no point have i said anything about performance. you claimed that a raycast is more reliable which has nothing to do with performance and is obviously not true since they both work. but one doesn't require you to pass an unnecessary direction to the method
You're just weirdly angry and confrentational in a discord help form lol
especiall CODE BEGINNER
and this conversation is useless since you're apparently incredibly opinionated about raycasts so i'm just going to block you 🤷♂️
Lol alright, block me, anyways...
@frigid sequoia Boxfriend is trying to "one up" you over pointless stuff, both solutions will work, it's just about what makes more sense and is more easily grasped by you conceptually
it's beginner code, it's meant to work, not be the best lol
You were the one one-upping with your just use X suggestion
boxfriend had a whole convo and you came in to offer a pointless change that you couldn't justify
I'm not one upping, I'm providing forward direction, just use it as in just try it, it will most likely do exactly what they were trying to do
I came in and dude cussing at the other
that's not helpful or friendly
I mean, I do get that sometimes I am recommended to use a unnecesarily convoluted way just cause it's the right way, even though a way simpler but not as efficient or accurate method would have work perfectly, but I mean, I wanna learn the RIGHT way to do it
I just feel that you are sometimes dropping stuff that I am like extremely confused about knowing this is specifically begginer level. You cannot expect me to know the whole coding api