#💻┃code-beginner

1 messages · Page 593 of 1

rich adder
#

ohh was just pointing out the instantiate function is static it can be called outside monobehavior

inland cobalt
rich adder
inland cobalt
#

im using unity engine but Destroy and Instantiate are both not defined

#

Nevermind, i needed to do object.instantiate

#

im stupid, cheers

rich adder
#

You can also do UnityEngine.GameObject.Instantiate

tardy inlet
#

Does anyone know how to fix this error?

burnt vapor
#

Please properly share your !code and indicate what UIHandler.cs line 32 is

eternal falconBOT
burnt vapor
#

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

tardy inlet
#

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");
   }
}
tardy inlet
burnt vapor
eternal falconBOT
burnt vapor
#

That said, what is line 32?

barren vapor
tardy inlet
#

i believe it is cs m_TimerDisplay = -1.0f;

#

my bad

#

m_NonPlayerDialogue.style.display = DisplayStyle.None;

rich adder
tardy inlet
#

gang i just need help with the pop up system 💔

hot laurel
#

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

tardy inlet
#

my bad, havent cleaned it up from what i was trying earlier

hot laurel
#

check if you dont mispelled NPCDialogue or if the element exist

north kiln
#

It's not okay to post here without using an IDE, as it's a waste of everyone's time--especially your own

hot laurel
visual linden
tardy inlet
hot laurel
#

you didnt set tag for that GameObject then

burnt vapor
#

The fact your school even has you write in notepad is absolutely insane

north kiln
#

Better? That's not an IDE at all lol

burnt vapor
#

Like writing on a piece of paper

#

Well yeah, it's not even an IDE. Just get an IDE lol

hot laurel
#

well it wasnt on paper sheet so its still not that bad

hot laurel
tardy inlet
#

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.

visual linden
hot laurel
carmine wasp
#

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

grand snow
visual linden
hot laurel
carmine wasp
tardy inlet
visual linden
# carmine wasp I'm not that new, i would just need someone to help me set up collaborate or som...

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...

▶ Play video
burnt vapor
# carmine wasp Hello, i am new to Unity and Programming as a whole, i would need some help from...

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...

▶ Play video
#

Also look up "Git LFS" for large file support when it comes to Unity.

hexed terrace
visual linden
#

Also please don't use Github Desktop 😅

burnt vapor
#

Citation needed

hexed terrace
#

Github Desktop is fine for beginners/ non-devs

#

(and more experienced people if that's what they're happy with)

burnt vapor
#

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

hexed terrace
#

I've mentioned it loads, which I originally found out about because of ... vertx or fogsight suggesting it years ago

visual linden
#

I'm a big fan of Fork, but you also have SourceTree

hexed terrace
#

SourceTree is to be avoided though 😄

#

Piece of shit that it is (or was when I last used it years ago)

grand snow
visual linden
#

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

grand snow
#

tried git fork ages ago but had some weird problems that made me ditch it

hexed terrace
#

GHD is super simple though, it's easy enough to work out

iron otter
#

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;
    }```
grand snow
#

😐 java moment

grand snow
visual linden
iron otter
grand snow
hexed terrace
iron otter
visual linden
carmine wasp
# hexed terrace Github Desktop is fine for beginners/ non-devs

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.

grand snow
burnt vapor
# iron otter Hi, I am a bit confused, ... if he(refers to speaker in the tutorial) had to mak...

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.

burnt vapor
#

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.

iron otter
#

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?

burnt vapor
#

And, like I said, it's just a more convenient way to specify get and set methods

burnt vapor
#

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.

iron otter
#

got it thanks

grand snow
burnt vapor
#

It doesn't really matter what it is

#

The point was explaining how a property works

#

Just the JIT bit is unrelated (removed now)

grand snow
#

which is out of scope of their initial query

burnt vapor
#

It's not, this is how a property works and why it's different from a field

hexed terrace
#

convo/ explanation was pretty much over - no point really complaining about it

visual linden
#

Well, the explanation was over, which is why the additional technical explanations risk creating confusion.

iron otter
burnt vapor
#

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

iron otter
#

coming from python, C(never used it but I can understand C code) and TS, CS indeed have some extra syntax

burnt vapor
#

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.

iron otter
#

okay

hot laurel
#

or use JetBrains dotPeek to directly view your assembly .dll so you can see the c# code and corresponding IL code

iron otter
#

I use VSCode and I like it, I also use it for all the languages I use

hot laurel
#

its a tool to view assemblies, not IDE

iron otter
#

oh nevermind

burnt vapor
fluid mantle
#

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

hot laurel
#

with dotPeek i can directly see the assembly as C# and IL code or low-lvl C# also it refresh auto

#

like so

burnt vapor
#

Tbh I haven't tried Linqpad enough yet to know what it can do

#

Dotpeek is paid tho

#

Oh it's free

hexed terrace
hot laurel
#

and include inspector view of how those missing in build elements are assigned

#

and where they are placed in Assets

willow shoal
#

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);
        }
    }
}
tardy inlet
#
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
visual linden
willow shoal
#

thanks

visual linden
#

Oh no wait

#

You're right

hexed terrace
#

I've just helped them in #📲┃ui-ux - the UI TMP was deleted, and a 3D TMP created.

#

There's no code issue here

tardy inlet
hot laurel
#

so did u tag the object in inspector?

#

press on this and screnshoot the inspector top bar or whole

tardy inlet
hot laurel
#

u have there the component?

visual linden
#

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.

tardy inlet
#

everything else is untagged too.

hexed terrace
#

If that object is permanently in the scene, then doing Find is pointless (and silly). Expose the reference and assign it

grand snow
#

yea stop using a tag its not helping you out...

timber tide
#

Woah woah woah. This is a tag-free zone

hot laurel
#

anyway keep searching for tag and component for static gameObject looks bad

visual linden
#

Great opportunity to try out the debugger in Rider ;)

hot laurel
#

debug logs all the way

timber tide
#

I wish there was some middle ground for debugging update loops

#

either spam your console, or continuously step through it

visual linden
#

Conditional breakpoints 😋

timber tide
#

oh yeah true. Effort though

tardy inlet
#

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

dense dagger
#

Does the runtime Scroll View support touch input (scroll on drag) on mobile?
If so how can I activate it?

hexed terrace
#

yes - dont need to do anything special

timber tide
#

I would expect mouse controls to translate into touch pretty easily

#

otherwise just register touch points as pointer events

dense dagger
#

Yeah same - and it is not working 😦

#

Only the scroll wheel works

hexed terrace
#

you need an active event system in the scene

dense dagger
#

Is there a documentation?

hexed terrace
#

yes

dense dagger
#

Would you be so kind and point me to it? I´ve been looking for ages how I can do this drag scroll

hexed terrace
#

google -> unity scroll view with touch

timber tide
#

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

dense dagger
#

Yeah that is why I am struggling

hexed terrace
#

so... you're using the new input system?

dense dagger
#

Yeah

hexed terrace
#

That's rather important information you should have shared with your original question.

dense dagger
timber tide
#

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)

dense dagger
#

Ill figure something out aight aight

timber tide
#

Also try getting it to work with mouse control first if you havent

frigid sequoia
#

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?

verbal dome
frigid sequoia
#

Yeah, I am, I need the raycast to come from a different plane than the rest of game

dark spade
#

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?

eternal needle
timber tide
#

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)

verbal dome
frigid sequoia
verbal dome
#

Make what work? I'm missing a lot of context here

frigid sequoia
#

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

frigid sequoia
#

I could laso kinda just... make an empty collider that follows the map possition to do that I guess...

verbal dome
#

To directly check what is on your cursor

#

(Ortho or perspective camera?)

dark spade
frigid sequoia
visual linden
eternal needle
#

you'll likely be casting downwards anyways if you're manually handling gravity

#

for a player, you should also manually handle gravity

visual linden
#

Raycasting risks missing ledges though, only drawback

verbal dome
#

Sphere/CapsuleCast also gives a smooth average of the hit normal

#

Where raycast does obviously not since it's just a single point

eternal needle
visual linden
verbal dome
visual linden
eternal needle
verbal dome
eternal needle
#

i feel i wrote that message clearly 😅

timber tide
#

I actually like the multiple collider idea

visual linden
#

Do we all collectively need a refill on our coffee?

timber tide
#

I would just overlap around your character to check all colliders, but use the additional colliders for information

dark spade
eternal needle
#

its as if you moved the capsule in a line

timber tide
#

someone make me a 3D collider cast API call so I can stop whining about how box2D has it and not physx API

verbal dome
#

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

dark spade
#

Would I want to make the cast just a smidge smaller than the original to not catch anything it is touchning from the side?

verbal dome
eternal needle
#

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

eternal needle
dark spade
#

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...

eternal needle
# dark spade Good point lol

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.

dense dagger
eternal needle
late badger
#

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

hexed terrace
hexed terrace
eternal falconBOT
dense dagger
hexed terrace
winter creek
#

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 ?

late badger
hexed terrace
#

"Audios" isn't clear on what you mean

late badger
#

Audio source

hexed terrace
#

has it been enabled?
was it enabled earlier than you think and therefore already played it's sound?

late badger
#
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);
    }
}
late badger
#

its loop too sorry 😭

#

its just background music

hexed terrace
#

that code isn't relevant

late badger
#

It's the only one I have on it

hexed terrace
#

all that does is create a singleton of the AudioManager.. nothing else.

#

It's definitely not managing anything

late badger
hexed terrace
#

delete from here and ask in #📱┃mobile - build errors aren't usually code issues.

fiery elk
#

alright thanks.

late badger
#

Like how would I check if there are more than one of these scripts in the scene

hexed terrace
#

t:AudioManager

late badger
#
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 😅

hexed terrace
#

what... how did you get "change the code" from "search for the type" with a screenshot of the hierarchy search..

late badger
#

Idk 🤷‍♂️

#

It works tho lol

hexed terrace
#

a needless change ..

tender stag
#

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

polar acorn
tender stag
polar acorn
tender stag
#

there has to be some way

polar acorn
#

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

tender stag
# polar acorn No, there isn't.
- 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

grand snow
# tender stag

issue is you need to offload to an instance sooner to access the serialized variables
or stop using Init on load

tender stag
#

yeah now awake will run before the initialize

#

i can use the AfterSceneLoad instead of BeforeSceneLoad

grand snow
#

why not use Awake only then?

tender stag
#

what

grand snow
#

wasnt the problem you wanted to access instance fields from a static function?

#

you do you

grand snow
#

i do

red igloo
#

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

polar acorn
#

So, just normal first person movement, except you hold the mouse button to go forward instead of W?

crystal fulcrum
tender stag
#

thats a bunch of bullshit then

#

since my console is printing out 2 then 1

polar acorn
#

Is this object already present and active in the scene before it starts, or is it spawned in?

tender stag
#

right im loading this scene again

#

so it goes awake, then initialize, then awake again

marble hemlock
#

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?

polar acorn
#

Triggers do not physically "exist". An object can move through them freely

rocky canyon
marble hemlock
#

AH

rocky canyon
#

both sends a CollisionMessage.. its just how the rigidbody interacts with it

marble hemlock
#

i see
thanks

polar acorn
rocky canyon
#

@marble hemlock ☝️

marble hemlock
#

one is for overlapping and one is to track hits like if it were a rigidbody

rocky canyon
#

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)

marble hemlock
#

i see
i know what i must do

#

once again thank you both 🫡

rocky canyon
flint light
#

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

flint light
rich adder
#

what is testCube prefab look like

flint light
rich adder
#

idk if it might be confusing that somehow

flint light
#

its imported like this for some reason

#

but ya thats the mesh

swift crag
#

That is correct.

rich adder
swift crag
#

The main asset is a model prefab.

#

When you drag testCube into the scene, you get a prefab instance

flint light
swift crag
#

"Cube" is a Mesh. It's a sub-asset.

rich adder
#

thats where you can attach components on

trail bloom
#

is there someone who can check my code? I am having a trouble about playerprefs

swift crag
#

You've created another prefab, also named "testCube"

eternal falconBOT
swift crag
trail bloom
#

idk what is that mean

rich adder
#

read it. posting code instructions

swift crag
#

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")

flint light
#

so the code is fine its just my prefabs are messed up?

swift crag
#

Here is an example.

#

I created the variant by right-clicking the "Skyscraper" asset and then going to Create > Prefab Variant

rich adder
#

no components

flint light
swift crag
#

an empty game object can't "have a mesh"

rich adder
#

oh i guess it doesnt add the mesh renderer

swift crag
#

This is not allowed when using Resources.Load

rich adder
#

idk I dont spawn that way I use like a sane person fields

flint light
swift crag
#

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

rich adder
#

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

lament harness
#

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

swift crag
#

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

flint light
swift crag
#

If you drag the model prefab into the scene, do you see anything?

flint light
#

im generating a random number of cubes

swift crag
#

or is it an empty-looking game object?

rich adder
# flint light how can i do that

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

flint light
swift crag
flint light
swift crag
#

it's just very small

flint light
swift crag
#

check the model prefab's scale (:

#

[100, 100, 100]

flint light
#

the model doesnt even have a prefab as a component

#

or a

#

anything

swift crag
#

You just dragged it into the scene.

lament harness
swift crag
#

That is a model prefab.

rich adder
flint light
#

ohh oe

swift crag
#

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!

rich adder
flint light
swift crag
#

Correct.

#

The "natural size" of the mesh winds up being 1cm for every unit in Blender

#

rather than 1m for every unit

rich adder
lament harness
# rich adder you want to grab the enemy from the player ?

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

flint light
#

im even more confused now i can change the object's prefab in the hierarchy and it works

swift crag
flint light
swift crag
#

ah, yes

flint light
#

if i just replace it with the prefab it works perfectly

swift crag
#

This completely replaces the object with a prefab

flint light
#

ohh okay

swift crag
#

And the prefab has a scale of [100,100,100]

rich adder
swift crag
#

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)

lament harness
#

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

rich adder
#

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.

atomic holly
#

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;
    }
rich adder
#

well

#

if you use WaitForSecondsRealtime it works fine
not if the gameobject is disabled ofc*

swift crag
#

Indeed. It takes an infinite amount of time for 0.5 seconds to pass in-game (:

rich adder
#

don't they both do Damage to a Health component ?

lament harness
rich adder
#

they both have input if you think about it

lament harness
rich adder
#

this way also know how you plan on grabbing the other to do damage

lament harness
rich adder
#

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
lament harness
#

i probably just did it very ineffectively cus i copied and pasted some code from playershoot() to make my enemy shooting

rich adder
lament harness
lament harness
# rich adder send the script, they can probably be made more modular so you dont even need to...
{
    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;
    }

} ```
rich adder
lament harness
#

💀

rich adder
#

no problem, in coding we try to avoid this

#

DRY - Dont Repeat Yourself

lament harness
#

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?

rich adder
#

with a few bools you can make this modular

eternal falconBOT
rich adder
#

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);

lament harness
#

yea

#

fair enough

void dawn
#

What do I do ?

rich adder
#

use a bit of common sense

void dawn
#

Sorry

#

I'm new

#

What do you need

slender nymph
void dawn
#

Ok I will post a screenshot of my code here

slender nymph
#

!code

eternal falconBOT
slender nymph
#

make sure the particle system isn't being instantiated as a child of hte object being destroyed

severe nymph
#

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)

slender nymph
#

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

void dawn
#

` 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);
}

} `

swift crag
#

that doesn't mean you should paste the entire thing into discord..

severe nymph
#

Thank you boxfriend, i'll come back in a minute with the new version

slender nymph
#

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

severe nymph
#

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

slender nymph
#

that's not how that works

severe nymph
#

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

compact stag
#

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

slender nymph
#

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

astral falcon
#

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

compact stag
#

yeah, so, it is a prefab

#

dragging a scene object into a prefab doesnt work? why is that?

slender nymph
#

assets like prefabs cannot reference scene objects because while the assets always exist, the scenes are not always loaded

astral falcon
#

Because prefab is just a blueprint of something you can copy into runtime

slender nymph
compact stag
#

thank you guys!!

slender nymph
#

this is a code channel

tame thorn
#

oh okay

#

i moved it to the art-asset-workflow channel, is that the right one?

fervent escarp
#

is it better to make a custom friction system or just settle down with unity's physics system?

astral falcon
fervent escarp
astral falcon
fervent escarp
#

fair enough

keen dew
#

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

swift crag
#

friction is applied when objects are touching each other; linear and angular damping cause a rigidbody to constantly lose linear or angular velocity

errant shore
slender nymph
errant shore
#

whad

slender nymph
#

read the page

errant shore
#

I only need the 2d and 3d core right?

slender nymph
#

huh?

errant shore
#

this

#

yk

rich adder
#

yes

errant shore
#

ok thanks

rich adder
#

also you should keep VS in english if you ever have errors or issues much easier to get help

slender nymph
# errant shore

typically you would refer to a workload using its title, not two random bits of info in its description

errant shore
#

wait chatgpt help

slender nymph
#

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

errant shore
#

oh my gawd i understand

#

yes that makes sense

#

thanks

#

do you guys ever made some games?

rocky canyon
#

nope, i use unity as a screensaver

errant shore
#

i mean like

#

games

#

on steam

#

yk

stone heron
#

I use unity to do my dishes

woeful carbon
#

anyone know how you would go about scripting spacing between multiple companion AI's that would follow you around

rocky canyon
#

lol.. i've not published to steam..

#

but its on my bucket list

slender nymph
errant shore
#

soryy

#

im young

slender nymph
errant shore
#

I will write correctly now.

rocky canyon
#

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

woeful carbon
stone heron
#

what are you using

errant shore
slender nymph
#

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 🤷‍♂️

woeful carbon
stone heron
#

oh

rich ice
stone heron
#

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

rich ice
stone heron
#

its not the player its each other

woeful carbon
stone heron
#

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

woeful carbon
#

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

rich adder
#

pretty much any formations type algorithm will probably help you out, iterate and spread em

rocky canyon
#

thats one of the most common problems for AI crowds..

#

best of luck

#

Ai Grouping.. Spacing.. etc

stone heron
#

its not really a code-beginner issue tbh

rocky canyon
stone heron
#

theres a lot of ways to go about it and it highly depends on the behaviour u want

rocky canyon
#

just start going down the rabbit hole 🐰

cold mist
#

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.

rocky canyon
#

if thats the type of game you're wanting to make then sure..

cold mist
#

idk if you guys ever heard of this series

rich adder
rocky canyon
#

whether u succeed or fail.. its gonna expose u to the things u need to learn about for that genre

cold mist
stone heron
#

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

cold mist
#

@rocky canyon @rich adder thanks for the heads up

rich adder
#

dont sleep on the Unity learn site it has really good content

cold mist
#

i won't

rich adder
#

unity youtube channel also been resuming posting good tutorials for their new packages

stone heron
#

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

errant shore
cold mist
#

but i checked a few days ago and it had an error

#

ill do the dark souls series until its up again

rich adder
cold mist
#

yeah

rich adder
#

cause the link changed and they havent redirected it yet

cold mist
#

or am i in the wrong place perhaps

cold mist
stone heron
#

guess those programmers need to "learn" how to make a link work properly

cold mist
rich adder
#

its working for me

stone heron
#

same

rich adder
#

try clicking to "explore our learning pathways" and click it again

cold mist
#

same problem

rich adder
#

try clearing browser cache

woeful carbon
swift crag
#

seems okay for me too

#

(safari)

rocky canyon
#

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

cold mist
#

8 years old tho, Do you think thats gonna be a problem?

swift crag
#

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

cold mist
#

@rich adder ty

#

it worked

slender nymph
#

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

rocky canyon
#

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..

rocky canyon
cold mist
#

alrighty

swift crag
#

javascript, you mean

rocky canyon
#

or Monoscript.. if its in c# u good lol

swift crag
#

or, god forbid

#

BOO

errant shore
#

Question isn't there a console tab anymore? Can't add it

rocky canyon
swift crag
cold mist
#

i'm gonna use the playlist as a starter

rocky canyon
#

thanks for having my back

cold mist
#

then i'm gonna go to essentials

#

then i'm going to do my own thing

#

or atleast try

#

thanks for the tips

swift crag
rocky canyon
#

c# structure.. how to add code to ur gameobjects, etc

errant shore
# rocky canyon

thanks thanks I tried to add it at the right mid not on the windows tab lol

cold mist
#

can you even code in java on unity?

rocky canyon
#

theres all types of plug-ins

#

but c# is its what it runs

swift crag
rich adder
rocky canyon
#

eww

swift crag
#

Oh noooooooooooo

#

Oh, this is for Android, I guess

rocky canyon
#

mmhmm

swift crag
#

That would make sense for writing glue code

slender nymph
#

yeah it supports java in the same way it supports c++, as native plugins (but only for android in the case of java)

rocky canyon
#

the only code ive ever heard of being used with unity is Python..

#

and thats b/c of machine learning

cold mist
#

i'm kind of new to programming languages cus i always programmed in built-in languages on engines like gd-script and gml

swift crag
#

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

rich adder
rocky canyon
slender nymph
cold mist
#

i got to ep 10

rocky canyon
#
  1. lol
rich adder
rocky canyon
#

i always have 4 projects open..

#

i like to use my PC as a bedroom warmer

swift crag
#

I had five open earlier

#

it was a bit silly

rich adder
rocky canyon
#

and i've yet to have a processing problem..

cold mist
#

and it was like: gd script you make eggs.
c# you make the fire, the pan and THEN you make the eggs

rocky canyon
#

as long as there's only 1 that im actively working on the other instances doesn't seem to hurt anything

cold mist
#

LOL

swift crag
#

uh oh

cold mist
#

was that a bad idea

rocky canyon
#

be careful with search-salad chatbots

#

just do ur research..

cold mist
#

mostly the basics

#

not everything on chatgpt

rocky canyon
#

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

hot laurel
#

i wouldnt trust a word from chatgpt

#

always ask for sources

rich adder
#

sadly next gen gonna be so "AI" bound they will have 0 critical thinking abilities

rocky canyon
#

next gen? lol...

hot laurel
#

well thats good, no competition

rocky canyon
#

heck ya 💪

cold mist
#

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

rich adder
#

!docs

eternal falconBOT
rocky canyon
# cold mist no chatgpt/AI bots as a resource

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 😉

rich adder
rocky canyon
rich adder
#

good to bounce conversations with nothing much more

rocky canyon
#

^ brainstorming ++

hot laurel
#

(delete AI comments, nobody will know that its AI code then)

until you doesnt know what it does, then you are busted

rocky canyon
#

trust.. lol

swift crag
cold mist
swift crag
#

[very loud explosion sound]

cold mist
#

in like "what does private void do in unity?" or sum

rich adder
rocky canyon
#

wellness check @ Fens place..

#

^ this is the underlining problem..

rich adder
#

it tries to prioritize appeasing your keywords rather than giving you correct knowledge

cold mist
rocky canyon
#

its transcended into an ass-kissing machine

#

lmao

rich adder
#

Unity tried to tie AI with their own Docs and it was pretty miserable

#

nothing can replace your own experience and knowledge gained

rocky canyon
#

100% agree...
you learn sooo much more from trials and errors

rich adder
#

ML training can to but the data its trained on isnt verified or accurate

cold mist
#

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

rocky canyon
#

ahh, the Rinse and Repeat of game-dev

#

you're forgetting the table flip tho

#

(╯°□°)╯︵ ┻━┻

hot laurel
#

all good until you dont wipeout 4k hours project

rich adder
#

you have to break through that just by expanding your knowledge on other things and take a break let problem marinate

swift crag
#

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

cold mist
#

most of it was like a roller coaster tbh

rocky canyon
#

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

cold mist
#

"im the worst, i'm never fixing this" to "yep, im the best programmer there is"

rocky canyon
cold mist
#

!docs

eternal falconBOT
errant shore
#

guys coding is like learning vocabs right?

#

hard vocabs

rocky canyon
#

b/c its Legacy Doodoo

#

use TextMeshPro

rich adder
#

you came here to ask about text no?

#

also not really code question

rocky canyon
#

no.. they're two different types of components

rocky canyon
#

you can use the same Font

#

but you'll need to generate a TMP font atlas

#

Window >

stone heron
cold mist
#

alr ill go to bed, @rocky canyon @rich adder thanks again. I'm genuinely grateful

cold mist
stone heron
cold mist
#

everytime i hear someone talk abt javascript is always something bad

stone heron
#

learning the keywords is pretty easy comparatively

#

the hard part is syntax and problem solving

stone heron
cold mist
#

really?

hot laurel
#

no way

cold mist
#

what are they really

stone heron
#

yep

rocky canyon
#

ya, two different scripting langauges

hot laurel
#

its not like script of java?

cold mist
#

are both of them a language?

hot laurel
#

a javascript

rocky canyon
#

javascript is used mainly for web-dev

stone heron
#

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

swift crag
stone heron
#

but yeah they have about as much in common as c# and python

#

errr well idk

#

pythons syntax is different

rich adder
swift crag
#

the proper name is ECMAScript

stone heron
#

the biggest thing they have in common is that they both suck and should be avoided whenever possible

#

in favor of better options

swift crag
#

at least, that's the name of the standard

stone heron
#

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

hot laurel
#

you dont have other options for in-browser scripting tho

rich adder
#

JS is pretty much the way until webassembly gets standard

stone heron
#

typescript is an option ive been told

rich adder
#

if you enjoy c# and type-safety at least use typescript

teal viper
#

There's also flutter or whatever it's called

hot laurel
stone heron
#

what

hot laurel
#

people who use ts to get static types tend to use as any type

#

making it usless

stone heron
#

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

hot laurel
#

it solve errors

swift crag
#

Typescript lets you gradually adopt proper static types

stone heron
#

dont ask me how that works

wooden nacelle
#

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.

swift crag
#

you start out with a giant mess of "any" and then gradually introduce actual types

hot laurel
#

until there its error and you back to use any

stone heron
swift crag
#

if you have zero interest in writing working code, then yes, you can do the obviously wrong thing

stone heron
rocky canyon
#

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

stone heron
#

theres also snapping and stuff

#

also the blocks are finding an open position

rocky canyon
#

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

stone heron
#

which is probably non-trivial

#

def not a "code beginner" project if u want those exact features

swift crag
#

my grad school's data structures class used Tetris as one of the homework assignments

stone heron
#

you basically have to make tetris ya

#

just unity physics and colliders wont cut it

#

not if you want something consistent

rocky canyon
#

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 😉

stone heron
#

resident evil

north kiln
#

It seems to have no physics at all, it's just interpolating between the point before a move was taken and after

stone heron
#

they fall

north kiln
#

it just happens to be that the position after is down

stone heron
#

if that counts

swift crag
#

Yeah, I would absolutely not want to try to smash this together with actual physics

rocky canyon
#

the grid is the real star 😉

stone heron
#

"physics on a grid"

swift crag
#

You want to be able to ask "can this piece fit into this space?"

#

the rest naturally comes from that, really

swift crag
#

can it fit one space down?

#

repeat until it can't

stone heron
cosmic dagger
wooden nacelle
# stone heron - what is your approach - what is your problem

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.

stone heron
#

can you be more specific than "not working"

#

but again as others said you probably dont want to be using rigidbody physics

rocky canyon
#

u were on the right track..

rich adder
swift crag
#

Physics colliders are useful when you can't easily decide "is X interacting with Y?"

rocky canyon
#

grid creation
piece movement
piece placement

swift crag
#

If you're on a grid, you probably don't have that problem

stone heron
swift crag
#

LLMs require an absolutely catastrophic amount of data, yes

#

(that's the secret sauce)

stone heron
#

idk what they fed it or how it works but I feel like data + time is king

swift crag
#

that's also why we've...run out of data

stone heron
#

nothing else is really worth much

rich adder
wooden nacelle
swift crag
#

wrong answers, at scale

stone heron
rocky canyon
#

possibly could have fixed that w/ offsets..

swift crag
#

well, that's unfair: that's what you'd get if you trained it on Stack Exchange comments

rich adder
rocky canyon
#

ur piece was probably snapping to the Intersection of grid lines.. and not the spaces between them

stone heron
wooden nacelle
#

I will check it

ripe shard
# swift crag wrong answers, at scale

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.

swift crag
#

Remember that you need to unalive the child process

ripe shard
#

XLLM <-- actually looks like a superbowl

rocky canyon
#

1040 😉.. my GPU is a MMLXXX-TI >8)

ripe shard
#

more like 5090Ti

wooden nacelle
rocky canyon
#

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?

ripe shard
#

also fun, openAI beat microsoft at the worst poduct naming olympiad

swift crag
#

microsoft 365 (good luck)

wooden nacelle
ripe shard
rocky canyon
#

i'll see if i can't find some specifics on how its actually done

swift crag
swift crag
rocky canyon
#

^ so im on the right track i guess

swift crag
#

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)

rocky canyon
#

snapping and downwards movement would be the first thing i tackled.. and once thats sorted the rest would be the home-stretch

frigid sequoia
#

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?

north kiln
frigid sequoia
#

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

rocky canyon
#
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..

north kiln
rocky canyon
#

ah tru.. i use raycast for perspective.. i thought he was refering to a 2d project tho. mb

north kiln
#

Who knows, might be

rocky canyon
#

waiting for confirmation 🙂 lol

north kiln
#

I'm sure they can figure it out, they have been given loads of options

rocky canyon
#

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

frigid sequoia
#

I eneded up just doing this

rocky canyon
#

yup, thats fine too. (keeping it where it already is on the Z)

nimble apex
#
    [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?
slender nymph
#

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

slender nymph
nimble apex
#

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

slender nymph
#

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

nimble apex
#

damn

#

i guess out of coincidence it really can spawn things out correctly lol

slender nymph
#

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?

obsidian citrus
#

How do you get the code blocks in discord

slender nymph
#

!code

eternal falconBOT
rocky canyon
#

don't the newer .NET actually order dictionaries?

rocky canyon
obsidian citrus
#

‘’’cs
//test
‘’’

slender nymph
obsidian citrus
#

That didn’t work

nimble apex
#

lemme modify it a bit lol

rocky canyon
slender nymph
#

that's because those characters were not `

nimble apex
#

maybe it will make more sense after this

#

ty👍

rocky canyon
obsidian citrus
#
//code
#

i got it

#

thanks

rocky canyon
#

im trying to think when i just wouldnt use a List instead i've not ran into a reason to consider dictionaries yet tbh

frigid sequoia
#

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?

slender nymph
#

show your current code so we can see how you are accomplishing this

frigid sequoia
#

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....

frigid sequoia
#

Oka, got that

hearty pollen
#

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;
    }
}
rich adder
#

Play keeps starting over the sound

#
if (birdIsAlive && (transform.position.y > 15 || transform.position.y < -15))
        {
            logic.gameOver();
            birdIsAlive = false;
        }```
frigid sequoia
#

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?

charred spoke
#

You can have multiple collider components on a single object

slender nymph
frigid sequoia
#

I kinda had to make colliders 3d so they would dettect Raycast from the camera...

slender nymph
#

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

frigid sequoia
slender nymph
#

what?

#

how are you performing these raycasts?

frigid sequoia
#

From the camera through the cursor towards a world point in the plane (at Z=0, which is basically where the whole game is)

slender nymph
#

i asked how

frigid sequoia
#

What do you mean how? A Raycast from the camera towards whenever the cursor is

#

What else can I say?

slender nymph
#

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

frigid sequoia
#

I did pass it already... There you go...

slender nymph
#

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

frigid sequoia
#

No, you should not, but you should not get mad either

slender nymph
#

anyway, i already gave you the answer so we're done here

frigid sequoia
#

So... basically does the same but works only with 2D... Why do we have two versions of that again?

slender nymph
#

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

frigid sequoia
#

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?

slender nymph
#

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

frigid sequoia
#

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

slender nymph
#

pretty much, yes. although it probably does work with a perspective camera too because 2d physics is still only in the XY plane

frigid sequoia
#

Kk, thxs

floral thorn
#

Just use raycast, not overlap. It's much more reliable for what you're trying to do assuming your box2d colliders are accurate

frigid sequoia
#

So I could use 2D colliders now, and... I use composite to combine them?

slender nymph
floral thorn
slender nymph
#

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

floral thorn
#

You're just weirdly angry and confrentational in a discord help form lol

#

especiall CODE BEGINNER

slender nymph
#

and this conversation is useless since you're apparently incredibly opinionated about raycasts so i'm just going to block you 🤷‍♂️

floral thorn
#

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

north kiln
#

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

floral thorn
#

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

frigid sequoia
#

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