#💻┃code-beginner

1 messages · Page 28 of 1

hushed spire
#

Tilemaps

#

[SerializeField] Tilemap[] animatedTiles;

teal viper
#

Share the whole code.

hushed spire
#

Gotcha, which website do you perfer

teal viper
#

And the error too.

teal viper
ivory bobcat
#

!code

eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

hushed spire
# teal viper And the error too.

"Assets\Scripts\DiscoFloorSpeed.cs(13,26): error CS1061: 'Tilemap' does not contain a definition for 'AddTileAnimationFlags' and no accessible extension method 'AddTileAnimationFlags' accepting a first argument of type 'Tilemap' could be found (are you missing a using directive or an assembly reference?"

teal viper
#

Try using Vector3Int as well as passing the actual flags as the second parameter(TileAnimationFlags.PauseAnimation).

abstract pelican
#
using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;

namespace Controls
{
    public class InputManager : MonoBehaviour
    {
        [SerializeField] private Camera sceneCamera;
        [SerializeField] private LayerMask placementLayerMask;

        public event Action OnClicked, OnExit;

        private Vector3 lastPosition;
        private PlayerInput playerInput;

        private void Awake()
        {
            playerInput = new PlayerInput();
        }

        private void Update()
        {
            if (playerInput.Building.Placement.triggered)
                OnClicked?.Invoke();
            if (playerInput.Building.ExitPlacement.triggered)
                OnExit?.Invoke();
        }

        public static bool IsPointerOverUI() => EventSystem.current.IsPointerOverGameObject();

        public Vector3 GetSelectedPosition()
        {
            Vector3 mousePosition = Mouse.current.position.ReadValue();
            mousePosition.z = sceneCamera.nearClipPlane;
            Ray ray = sceneCamera.ScreenPointToRay(mousePosition);

            if (Physics.Raycast(ray, out RaycastHit hit, 100, placementLayerMask))
            {
                lastPosition = hit.point;
            }

            return lastPosition;
        }

        private void OnEnable()
        {
            playerInput.Building.Enable();
        }

        private void OnDisable()
        {
            playerInput.Building.Disable();
        }
    }
}```

How to make clicks work on mobile devices as well?
hushed spire
hushed spire
summer stump
hushed spire
#

Well

teal viper
hushed spire
#

I have a different error now though

ivory bobcat
teal viper
hushed spire
#

I have both the old error and this new one:
Assets\Scripts\DiscoFloorSpeed.cs(13,75): error CS0103: The name 'TileAnimationFlags' does not exist in the current context

#

Ah

#

This was just me being dumb

#

Assets\Scripts\DiscoFloorSpeed.cs(13,85): error CS0117: 'TileFlags' does not contain a definition for 'PauseAnimation'

summer stump
# abstract pelican

There should be a touch binding. You'll have to figure out how to implement that. I think you can get a touch COUNT, so like if there are two, count that as right click?

teal viper
#

TileAnimationFlags is thecorrect enum

hushed spire
#

You right

#

Been at this for 5 hours don't judge

abstract pelican
teal viper
summer stump
hushed spire
#

Still have errors after using the namespace

hushed spire
abstract pelican
hushed spire
#

Specifically
Assets\Scripts\DiscoFloorSpeed.cs(14,75): error CS0103: The name 'TileAnimationFlags' does not exist in the current context
And
Assets\Scripts\DiscoFloorSpeed.cs(14,26): error CS1061: 'Tilemap' does not contain a definition for 'AddTileAnimationFlags' and no accessible extension method 'AddTileAnimationFlags' accepting a first argument of type 'Tilemap' could be found (are you missing a using directive or an assembly reference?)

teal viper
hushed spire
#

fixed now

teal viper
#

Does it fix the errors?

hushed spire
#

No

#

Side note; removed scenemanagement

teal viper
#

Where do you see the errors? In your ide?

hushed spire
#

Unity

teal viper
#

What do you see in the ide?

hushed spire
hushed spire
teal viper
#

??

hushed spire
#

At least nothing jumping out saying "errors here!!!"

teal viper
#

If you see nothing, then it's not configured properly

#

!ide

eternal falconBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

teal viper
#

Start from configuring it. After that we can move on to the errors.

hushed spire
#

Alrighty

hushed spire
#

Just giving same errors that I get in Unity

summer stump
#

Often your ide will suggest fixes

hushed spire
#

"Show potentiel fixes"

slender nymph
#

do you have using UnityEngine.Tilemaps in your using directives?

summer stump
#

But still, that would be it

hushed spire
slender nymph
#

ah, so the last error is due to omitting the Tilemaps. part of the type. the enum you are trying to use is Tilemaps.TileAnimationFlags

#

as for the first one, what version of unity are you using?

teal viper
hushed spire
#

checking unity version now

#

2021.1.34f1

teal viper
#

Actually that's correct. You don't need the Tilemaps there since you have it in usings.

slender nymph
#

yeah the enum and method were added in 2022

hushed spire
#

Wow

#

Making a backup before I update it

teal viper
#

2021 lts seems to support it too

hushed spire
#

Any reccomendations?

#

Oh

#

Nevermind than?

teal viper
#

Why are you on a beta version of several years ago lol?

hushed spire
#

I make a lot of sleep deprived decisions for quick fixes

teal viper
#

Update to 2021.3

hushed spire
#

This was probably one of them from a previous project

tame thorn
#

I have the main camera separate from the player, so when my camera moves vertically, the sword doesnt stay in the middle of the screen
how can i make it follow the vertical movement of the camera?

public class SwordController : MonoBehaviour
{
    public Transform swordCursor;
    public Vector3 defaultPosition;
    public Quaternion defaultRotation;
    public float rotationSpeed = 10.0f;

    void Start()
    {
        defaultPosition = transform.localPosition;
        defaultRotation = transform.localRotation;
    }

    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            if (swordCursor != null)
            {
                //Point towards SwordCursor Object
                Quaternion targetRotation = Quaternion.LookRotation(swordCursor.position - transform.position);
                transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
            }
        }
        else
        {
            // Smoothly move back to default position and rotation
            transform.localPosition = Vector3.Lerp(transform.localPosition, defaultPosition, rotationSpeed * Time.deltaTime);
            transform.localRotation = Quaternion.Slerp(transform.localRotation, defaultRotation, rotationSpeed * Time.deltaTime);
        }
    }
}
slender nymph
hushed spire
#

Aight give me a few minutes for a backup and an update

teal viper
summer stump
#

And 2022.2 NOT supported?

teal viper
#

Anyways, if you can afford it, better to update to latest lts(2022)

teal viper
hushed spire
#

Naaah I aint spending money

summer stump
hushed spire
#

I can afford it if it's free

summer stump
teal viper
#

They often start working on betas earlier than previous lts, so some of the previous version features might not be included.

teal viper
hushed spire
#

2022.3.11f1 good?

teal viper
#

Right, I mean if you're not afraid of breaking changes.

teal viper
hushed spire
#

So how breaking are we talking

#

Oh well I made a backup for a reason

slender nymph
#

probably better off just updating to 2021.3 tbh, less chance of features changing

hushed spire
#

Yeah i'm installing both

#

Gonna use 2021.3 for this project though

#

please wait for me my emotional support coders 🙏

#

Alright, opened with 2021.3

#

well, opening

#

@slender nymph @teal viper Opened in newer version, still same errors

#

trying 2022 now

#

still same errors

#

wait!

#

only 1 error now 🎊

#

Assets\Scripts\DiscoFloorSpeed.cs(12,75): error CS0103: The name 'Tilemaps' does not exist in the current context

#

it works

#

thank you box and dlich, 5/5 stars, kudos

teal viper
#

So it didn't work in 2021.3?

hushed spire
#

2022.3 was successful however

royal linden
#

how do i fix this

teal viper
#

Nvm.make sure that the index is within the bounds of the array.

royal linden
#

how

#

tho

slender nymph
#

items.Length is 1 index past the end of the array

teal viper
royal linden
#

no#

teal viper
#

Nvm. I'm not reading the code properly

#

Boxfriend is correct.

#

Why are you accessing something with that index?

#

Length is the last element index + 1 if that wasn't clear.
So it's out of bounds.

royal linden
#

so i cant use it?

teal viper
#

You can't use it as is. Why would you do though? What are you trying to do?

royal linden
#

spawn things

teal viper
#

I'm talking about that line specifically

#

What are you trying to do on that line?

royal linden
#

pick a random thing in it

slender nymph
#

well that's certainly not how to get a random object from an array

teal viper
#

Well, that's not how you pick a random thing.

rich adder
#

you need a random number , aka index within that array/list @royal linden

charred spoke
royal linden
#

how can i put the trees in the right position

#

they inside the ground

rich adder
#

fix da pivot

royal linden
bright kindle
#

im geting this error

ArgumentException: Input Button Escape is not setup.
To change the input settings use: Edit -> Settings -> Input
LevelManager.Update () (at Assets/Scripts/LevelManager.cs:83)

with this code

    if (Input.GetKeyDown(KeyCode.Escape))
    {
        Debug.Log("Sup");
    }

but the problem is even with the error poping up, its still working

rich adder
bright kindle
#

this is the same script

rich adder
#

then you didn't save

bright kindle
#

if (Input.GetKey(KeyCode.Escape))
{
Debug.Log("Sup");
}

north kiln
#

If your error is not underlined in red you need to configure your !ide

eternal falconBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

north kiln
#

Actually, that's a runtime exception... so no underlining

#

but navarone is correct

#

there is no issue in that code, it doesn't use GetButton, so it won't throw that exception

bright kindle
#

sorry let me explain
this is within my update fucnction and its showing no error during editor but when I start the game, its start giving this error while the game is picking up Escape key

summer stump
#

Make sure to hit ctrl+s in the ide, then clear errors in the console, then hit play again

bright kindle
#

yeah I have it every few seconds

summer stump
#

If the error pops up again, screenshot line 83 of the level manager script

bright kindle
#

now im getting this error

Cannot switch to actions 'Player'; input is not enabled
UnityEngine.InputSystem.PlayerInput:ActivateInput ()
LevelManager:Update () (at Assets/Scripts/LevelManager.cs:78)

rich adder
#

are you like mixing Input systems ?

summer stump
#

So are you using the new input? The other code was the old input manager

bright kindle
#

yes new input system

#

I actually tried looking how to do it with the new

#

couldnt find

summer stump
bright kindle
#

it

#

yes

summer stump
#

You should probably just share the script using a paste site

eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

bright kindle
ruby elk
#

Alright, I have what I assume is a logic issue here. I'm working on an inventory system for my game and this is the codes for the placement of the buttons. Currently I'm hardcoding the buttons to depend on each item rather than assigning an object to that button in the inventory. Everything works except for the setButtonPlacement function, it sets the button as active, but the placement of the button does not go to 0,0 as I'm trying to set it. the InventoryButtons list is a list of "Button" structs. I followed documentation I found online for changing button placement in code but for whatever reason its placing it around -700,-1000. Any ideas or info y'all need to help me?

summer stump
# bright kindle https://gdl.space/qoqinokoti.cs

I believe you have to actually enable the input (with playerInput.enabled = true) before you can call ActivateInput or DeactivateInput

Also, on line 83 there is no code. Is this modified from the previous error?

bright kindle
#

yes I modified it. I saw the issue there so I modified it

#

yeah it worked 🥹

#

I had to enable it

#

thanks

ruby elk
timber tide
#

Start throwing some logging in your code

#

And make sure the position isn't being changed locally

ruby elk
#

I have for everything else besides the last function because theres not much I can change on it besides that position that I can see in the inspector. I know the first line of code for the method is running so its not an issue of it not being called

summer stump
#

I would also say throw in a debug log with the actual position values being set

ruby elk
summer stump
#

There is transform.localPosition

ruby elk
#

Thats my problem then. Perfect I'll see if that works, thanks

#

Yessir that fixed it, thanks y'all

olive lintel
#

Hey guys, super odd question because I found a working solution to it but I have no idea why the solution works any differently at all but here goes.
The following code works:

if (triggerName != "")
        {
            triggerScript.addTrigger(triggerName);
        }```
However this code returns an index outside of array error(wtf???):
```if (getData.frames[actionIndex].triggerName != "")
        {
            triggerScript.addTrigger(getData.frames[actionIndex].triggerName);
        }```
I know it's really not an important question because I have found a solution but I'm trying to learn and genuinely curious/confused as to what the functional difference is between the two of these
#

(also I checked if the index error was occuring in the trigger script and it wasn't so idek man :/

wintry quarry
#

Also the types of the objects involved are not clear either

olive lintel
#

get data is a scriptable object and frames is a struct contained within it

wintry quarry
#

You'd need to show those types

#

frames seems to be a list or array btw, not a struct

cosmic dagger
#

how is frames a atruct? did you create an indexer for its fields?

wintry quarry
#

I'd guess they're confused and it's an array or list of a struct type

olive lintel
cosmic dagger
wintry quarry
#

It'd be better if you just showed the code

olive lintel
#

I changed it back to the old solution and now it works exactly the same so idek what happened...

#

I think maybe before I was adding 1 to the actionIndex variable or something and maybe I didn't save it beforehand I have no idea

wintry quarry
#

I'd guess you had something else before

#

That being said the first example in your code snippet above is much better

#

It's cleaner and more efficient

cosmic dagger
#

i would've logged the value of actionIndex beforehand, it was probably out of range . . .

slender nymph
#

also unrelated to the actual issue, but rather than checking if the string is equal to "" you could instead use string.IsNullOrWhiteSpace

random sand
#
{

    public ParticleSystem particle;
    
    void Start()
    {
        particle = this.gameObject.GetComponent<ParticleSystem>();
        particle.Emit(1);
    }
    void Update()
    {
        if (!particle.isPlaying)
        {
            Destroy(this.gameObject);
        }
    }
}```
hey everyone, i'm trying to make an impact system for my weapon. whenever a raycast hits a wall, a prefab with this script is created but i can't see the animation. any reason why this doesn't work?
teal viper
random sand
#

i just wanna ask is there a cheaper way of doing this?

#

there's a delay from when i click to when the animation plays

teal viper
#

Are you sure it's actually a performance issue?

#

If it is, use the profiler to troubleshoot it.

#

One possible issue is if you're spawning many of this particles every frame. This would cause a lot of work for the GC. In this situations it's advices to use an object pool.

random sand
random sand
teal viper
rare basin
#
public class UnitsCollectionController : MonoBehaviour
{
    public List<AddUnitToDeckButton> collectionSlots;

    private void Start()
    {
        PlayerDeck.Instance.OnUnitAdded.AddListener(RefreshCollection);
        PlayerDeck.Instance.OnUnitRemoved.AddListener(RefreshCollection);
    }

    public void RefreshCollection(int index)
    {
        foreach(var item in collectionSlots)
        {
            if(item.hasBeenAdded)
            {
                item.unitImage.sprite = item.unitData.unitSlotSprite;
            }
            else
            {
                if(item.unitData.unitSlotOffSprite == null)
                {
                    item.unitImage.sprite = item.unitData.unitSlotSprite;
                    continue;
                }
                item.unitImage.sprite = item.unitData.unitSlotOffSprite;
            }
        }
    }
}

I'm getting object reference not set to an instance of an object in line if(item.unitData.unitSlotOffSprite == null). Why is that? My unitData is referenced

#

Ok figured it out nvm

dry tendon
#

Hey, does someone know how can I create a good icon for my app created in unity for Android?

#

Cause in my phone, the icon that I've chosen it's blur

#

And it is not a resolution problem because I have exported it from Photoshop at a very high resolution

unique hull
#

Ive ran into a weird problem with a wage equation that wont return anything but 0.

float payfloat = (((worker.Wage*worker.Level) / 480)*50);

Worker.wage is an int at 100
Worker.level is an int at 1

I ran a debug for those values and that works correctly. But the payfloat never returns anything but 0 all the time.

Anyone have any idea what im doing wrong?

#

It should return ~10 in my books :/

north kiln
unique hull
#

I just did that and it works now. What in the world? , i thought if i didnt type "f" it was counted as that in this case

north kiln
#

No, you are performing integer division, and assigning the result to a float

#

float result = exampleInteger / (float) anotherExampleInteger; is how to do it when you have two integer variables

unique hull
#

Ahh. But i dont need a (float) infront of my wage*level part of the equation?

north kiln
#

As long as one of the arguments is a float, it will perform floating point division

loud dragon
#

I am having problem here as even after adding prefab to the gameobject in the inspector it is showing missing variable

unique hull
#

Ahh gotcha. Thanks alot , good to know for later equations. Save me some headaches 🙂

loud dragon
north kiln
#

Search the scene for that component and check what every one has it assigned

loud dragon
#

i have checked it

unique hull
#

You have no code in the start function that searches / resets the prefab?

loud dragon
#

no

north kiln
#

Can you show the hierarchy when you have searched t:Player_rotation

loud dragon
north kiln
#

Do both of those objects have the Bullet Prefab assigned?

loud dragon
#

no

north kiln
#

Then that's your issue.

loud dragon
#

thanks

#

in the above code my bullet object is just remaining static after shooting and is not moving forwarrd what should i do

unique hull
loud dragon
#

donethanks

vale blade
#

what is a good place to start building a chat interface similar to how you text on a phone? any components I should consider?
my plan is to make a prefab for a message, and then programatically add these to the window. I'm not sure how I'm going to handle eventual scrolling though?
I'm also unsure how I'll handle that some messages are longer than others, so they ll differ in height

gaunt ice
#

not code question
you may get started with scroll rect, content size filter, vertical layout group

amber spruce
#

hey so how do i set like a new key mapping thing

#

trying to make my player be able to sprint

vale blade
amber spruce
#

so in my player controller i want to add sprinting

#

this is the code i have rn for the sprint part

   if (Input.GetButtonDown("Shift"))
   {
      playerSpeed = playerSpeed * 2;
   }
#

will that work for if the shift key is pressed

unique hull
#

That would increase the speed everytime you press the button

#

You need to have a Basespeed variable and a current speed variable.

So when you are pressing shift - the currentspeed would be Basespeed *2 , and when not - currentspeed is basespeed

amber spruce
#
        if (Input.GetButtonDown("LeftShift"))
        {
           playerSpeed = playerSpeed * 2;
        }
        if (Input.GetButtonUp("LeftShift"))
        {
            playerSpeed = playerSpeed / 2;
        }

i have that aswell

#

oh wait no that wouldnt work

#
 if (Input.GetButtonDown("LeftShift"))
 {
    playerSpeed = playerSpeed * 2;
 }
 if (Input.GetButtonUp("LeftShift"))
 {
     playerSpeed = playerBaseSpeed;
 }

smth like this

unique hull
#

Id put it in the shift aswell

#

So playerspeed = playerbasespeed *2

#

Just incase something interupts the "Getbuttonup" function later on in your development

amber spruce
#

alright

unique hull
#

Like a menu , or something like that

amber spruce
#

but the part that gets if the button is down or not is good

unique hull
#

Yeah thats good.

amber spruce
#

so yeah it doesnt do anything

#

and i dont see any key for it in the input manager

unique hull
#

Ohh , have you not added the shift key to the input?

amber spruce
#

probably not

#

where would i do that

unique hull
#

Ohh this input system is new. I havent used it im affraid. I useually put in the keycodes instead of the input system.

So either you look up a tutorial for how to enter new inputs into that system or use : if (Input.GetKeyDown(KeyCode.LeftShift))

ruby elk
#

Or you can try and just get a value of that key (0-1) and use that

amber spruce
#

so how would i have it so it plays a certain animation while its active

ruby elk
#

within update,

if(keyvalue == 1 && animationNotYetStarted) {//keydown
doAnimation();
animationNotYetStarted = false;
}

#

the bool is so that it doesnt continually start over and over

amber spruce
#

doesnt it only do that animation once though

opaque jay
#

Hi, I've noticed my code isn't as colorful as when I check out tutorials, what makes my code show in different colors ?

amber spruce
opaque jay
#

I'll check that out :3

#

Thanks

eternal falconBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

ruby elk
amber spruce
#

ok thanks

amber spruce
#

now time to figure out how to make a push and pull mechanic where you can push objects and players away and pull objects and players to you

#

that will be fun lol

silk night
#

Wasnt there like a possibility to set up a default scene that you are loading in when editing a prefab? im trying to find it but I cant

#

Like editing a canvas prefab with a pre-set scene to emulate my other UI

loud dragon
#

hey i have made a small target prcticing game and have done everything but noow its not working properly its when colliding its not getting destroyed and giving points so was asking if someone can somehow help

keen dew
#

Can't help without seeing the code

rocky owl
#

Hello guys, do you know how i can enter in each element of this?

languid spire
rocky owl
#

from code

#

for assign the data to other object

unique hull
#

Is that an element you have made yourself ?

#

If it is , then you need to add a function to apply the values

short hazel
buoyant knot
#

it seems like a struct they made

rocky owl
#

in a for or foreach?

short hazel
#

Not necessarily

#

You can pass a number directly to access a specific element

rocky owl
#

i dont understand sorry. That's how I'm trying

short hazel
#

You can't use foreach here

#

Well, you can't use a numerical index if you want to use foreach

#

Just use the item variable

unique hull
#

index outside of the loop , but for is better in this case

short hazel
#

item.Id

rocky owl
#

but for example if the item have id 2 i cant assign the data that correspondent

#

?

short hazel
#

Well what do you actually want to do?

#

Access a single element of your list, to get or set a value, or go through all the elements of the list

rocky owl
#

I have an item and I want only by assigning the id to put all the other values such as description, etc.

short hazel
#

So you need to find an element that has a specific value in its Id variable

#

You can either use for, or foreach for those

unique hull
#

Ahh i see

rocky owl
#

Yes, but I have lists within a list

#

I need acces for example to element 0 and id of element 0

short hazel
#

There's no lists in lists here

polar acorn
unique hull
#

Theres a few ways you could do this.
I would use a master list with all the IDs and properties already filled in.

Then you run a foreach item (Inventory) Against a foreach Item(Masterlist)
And if they match - set the values to be the same as the master list item.

Or you could use a foreach loop on the items there and use a switch case on the ID's but thats not recommended.

short hazel
#

You do items[0].Id to access the ID of the first element in the list

rocky owl
#

sorry i dont understand too of programation

opaque jay
#

Erjoni, you want to go through all the Id values of your elements right ?

rocky owl
#

yes

opaque jay
#

yup, SPR2 has given you the answer

short hazel
#

For loop, foreach loop can both do that

amber spruce
#

so for my player controller script i have it set the playerbasespeed to 5.0f but in unity its set to 2 for some reason

#

public float playerSpeed = 5.0f;
public float playerBaseSpeed = 5.0f;

gaunt ice
#

editor will override the value in your script

unique hull
#

^

amber spruce
rocky owl
#

Im going to try

amber spruce
#

i guess i canjust edit it in the editor

opaque jay
unique hull
gaunt ice
#

make them private, or just edit them in your editor if you have multiple instances and them will have different speed

naive lion
#

What is the learning curve to advanced enemy AI in unity?

timber tide
#

just keep stacking them logic gates

broken anvil
#

hey what code do i use additionally to disable a component of a instantiated object

broken anvil
languid spire
#

no

broken anvil
#

where do i put what component i want to disable?

cosmic dagger
languid spire
#
GameObject go = Instantiate(gameobject);
MyComponent component = go.GetComponent<MyComponent>();
component.enabled = false;
broken anvil
languid spire
#

thats what the docs are for

naive lion
#

Also guys ive never tackled multiplayer before
Just for a basic overview, is it hell to set up AND test

languid spire
cosmic dagger
naive lion
#

o>

#

wish me luck

cosmic dagger
#

the road ahead is perliess and fraught with danger . . .

charred spoke
tulip tapir
#

Hi, i have made a Programm with whom i can open various Video- and Audioclips and since i need to store these custom made Clips somewhere and need to load them into the Program when i click a Button, i use the Resources Folder at the Moment. Of course, since these are quite a few Clips, i need to order them in a Folderhirarchy. Now i have the Problem, that the Program works in the Editor, but not when builded, i think because Unity turns the whole Resourcefolder into one File, so that the Code adressing the Folderstructure does not work anymore. Now, eventhough i could question now, why Unity even makes such a Code, that does not work when builded, in the first Place, but i just want to solve the Issue and load my Files at the Moment. Is there an

Option 1: A Command to load Files from the Resource Folder with respecting the File Hirarchy / Data Path, or

Option 2: Store Files in another Folder with another Load() Method, so that this Folder does not get turned into a File by Unity when building?

Example of useless Code:
Videoclip = Resources.Load<VideoClip>("Subfolder/Videofile");
// Works in Editor, but not in Build

cosmic dagger
#

@queen adder where'd it go?

#

i was reading . . .

queen adder
tulip tapir
polar acorn
stiff kettle
#

I have set up visual studio and everything works fine when i open VS directly from the desktop but when i open a C# script within unity the autocomplete and stuff doestn work? i am so confused?

eternal falconBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

stiff kettle
#

yes i have done that 2 times but it doestn work as intended

twilit trail
#

hey so i have an enum in a static class like this:

public static class Loader
{
    public enum Scene
    {
        MainMenu,
        SceneLoader,
        Lobby,
        CharacterCustomization,
        DemoScene
    }```

and i have accessed its ToString method before like this:
```cs
    public static void NetworkLoad(Scene target)
    {
        NetworkManager.Singleton.SceneManager.LoadScene(target.ToString(), LoadSceneMode.Single);
    }```
which gives the name of the scene, like Scene.MainMenu.ToString = "MainMenu".

i'm trying to use that in another script though and getting compile errors:

```cs
switch (sceneName)
{
    case Loader.Scene.CharacterCustomization.ToString():```

this gives me the error `The type name 'CharacterCustomization' does not exist in the type 'Loader.Scene'` which is weird because it does and also if I remove the ToString it resolves it perfectly but gives the error `Cannot implicitly type Loader.Scene to String` as expected.

what am I doing wrong?
languid spire
#

To start with your first code example does not access your enum.
Secondly you use ToString on an instance of a variable not of the type itself

polar acorn
#

You could store it in a variable and ToString that variable

#

and I think there might be a helper method in Enum that gets the string of a specified value

silk night
#

I feel stupid, this is like the 15th time im setting up ui stuff and now it doesnt work like it did the other 14 😄

I have

  • Event System
  • Graphics Raycaster on the main Canvas
  • Event Setup for the Button

Clicking it does nothing though, I installed the new InputSystem for the first time tho, any ideas what might be missing?

polar acorn
#

(Using the last overload on the page since you have the enum value and don't need to cast it from int)

polar acorn
keen dew
#

Switch cases must be constant values so the approach won't work either way

silk night
#

Yes

polar acorn
# silk night Yes

So, at the bottom of the inspector for your event system, you should see info while playing about what's currently hovered and selected and whatnot. Play the game, hover over your object that's not responding to clicks and see what your event system thinks is going on

#

You might have an invisible collider/raycast target in front of it

twilit trail
keen dew
polar acorn
silk night
#

Yes, but it only shows what I have selected in the hierarchy

#

Oh i should mention i am on the 1.8.0-pre version for the search field fix

polar acorn
#

Can you show the inspector of the button and your canvas

silk night
polar acorn
polar acorn
silk night
#

No I have that error figured out, its from the entitas library im about to fix that next

polar acorn
#

Can you get any UI elements to respond to the cursor, or is it just this one specific one that's not working?

silk night
#

and it reacts to hover & click

#

weird oO

#

well as soon as I put it into UIMainMenuScreen the reaction stops

#

oops, figured it out

polar acorn
#

Ah, I see, your sub-canvas has no graphics raycaster

#

only the main one does

silk night
#

Oh didnt know each one needs one, good to know, thanks for the help 😄

timber tide
silk night
#

welcome to floats

polar acorn
polar acorn
tulip tapir
polar acorn
timber tide
#

oh, maybe it has some ToString function that rounds yeah

tulip tapir
tulip tapir
silk night
#

If you put a file in a "Resource" folder

polar acorn
silk night
#

you can just get it by Resources.Load<Type>("Name");

#

oh nvm, missread what you are trying to do 😄

tulip tapir
#

maybe Resources.Load<>(Filename).GetFileName()?

polar acorn
polar acorn
tulip tapir
polar acorn
silk night
#

!code

eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

tulip tapir
loud dragon
#

in this both the objects are not colliding and are bypassing each other and are not destroying

swift crag
#

it's directly poking around in your project folder

#

None of these files will exist on disk in the built game. Everything will be stored in a few big asset bundles.

#

Resources.Load and Resources.LoadAll will be able to retrieve assets that are stored in a Resources folder.

#

These do not load "files". They load assets.

#

If you absolutely must think in terms of files (e.g. you want users to be able to add their own files or editing existing ones), you want StreamingAssets.

#

If you just want to know how many assets are found at a certain path, then call LoadAll and then check the length of the array

tulip tapir
#

How do i:
Array = Resources.LoadAll<Folder>(Subfolder);
Length = Array.Length?
count Folders in the Resource Folder with a Command? Without counting Subfolders wich are further down below in the Hirarchy?

polar acorn
swift crag
#

the folder hierarchy doesn't exist when the game is built

#

i am not aware of a Folder type

#

there's UnityEngine.WSA.Folder, which is some really specific thing for the Microsoft Store

#

What are you trying to accomplish here?

loud dragon
#

https://hastebin.com/share/opaxemijov.csharp
in this both the objects are not colliding and are bypassing each other and are not destroying

polar acorn
loud dragon
#

done

swift crag
#

you can follow these steps to figure out what's wrong

polar acorn
tulip tapir
# swift crag What are you trying to accomplish here?

I try to direct through Code through the Subfolders. Depending on what the User does, a different Sound has to be played
I guess i have to use a different approach and make a "case" scenario in the code, instead of doing it in the Hirarchy, sad, takes more work, but ok

loud dragon
#

is trigger is checked for both in collider

ruby elk
loud dragon
#

no for this i created an empty object for spwaning

rich adder
# loud dragon

ur moving with translation probably wont give accurate result either

ruby elk
#

still the same way. The OnTrigger needs to be on one of the colliding objects.

loud dragon
#

but if i do this than i cannot check the number of targets

valid finch
#

When handling online multiplayer do I need to set up my player controller in a different way? Just curious how it would work..

I just want to make sure I am building my game in such a way that it isn't extra rediculous to add multiplayer support into it. Any advice ? Any videos or recommendations on this? I don't want to build my system in such a way that I can't easily expand upon it and add the multiplayer in the future

ruby elk
#

For example, I have a sword in my game that is non-triggered and an enemy that is. I have the code on my enemy to detect on trigger and checks if the object is a sword. Gets the script on the sword (or bullet in your case) to check how much damage it did, and removes the amount of health from my enemy

ruby elk
loud dragon
#

how

rich adder
polar acorn
loud dragon
#

counter scripts is on spawn manger gameobject

polar acorn
loud dragon
#

none

polar acorn
loud dragon
#

both are different gameobjects

ruby elk
#

2 ways. If its a parent object (GameObject.parent) or GameObject.Find("Spawner").GetComponent<Counter>().count(); or ending with whatever public variable/method

polar acorn
#

I asked for the ones involved in the collision

#

So the Counter object and the thing you're expecting it to collide with

ruby elk
#

^

loud dragon
#

theses both are involved in collision but this script is attached to spwanmanage gameobject

ruby elk
#

Thats why I said your collision script must me on a colliding object

#

your spawner does not collide

loud dragon
#

no

polar acorn
loud dragon
#

prefabs attached to it collides

ruby elk
#

Its not attached, it only references it

tulip tapir
#

Can i do this with StreamingAssets?
Like:
StreamingAssets.GetFiles().Length;
?

valid finch
loud dragon
valid finch
#

I feel like I am not too far into it to where this will be a problem currently. I just wanted to make sure I prepare and build for it now, before it is a bigger issue

polar acorn
# loud dragon

You've cropped the SpawnManager inspector, where is the collider

loud dragon
#

what do you mean by collider

#

i am not getting it

ruby elk
#

You're giving us parts of the inspector, we can't tell what is what.

polar acorn
loud dragon
#

ok

rich adder
polar acorn
#

Both objects involved in the collision have to have a collider

loud dragon
#

they both have sphere collider

polar acorn
#

Show the collider on SpawnManager

valid finch
ruby elk
#

To help clear it up, there are 3 object. Bullet, enemy, spawner. Spawner has the counter script and no collider. Correct?

loud dragon
rich adder
polar acorn
#

SpawnManager has the script

loud dragon
#

yes

polar acorn
#

You are checking for a collision with it and something else

#

so show me the collider settings on the SpawnManager

ruby elk
loud dragon
polar acorn
polar acorn
loud dragon
#

okk

polar acorn
#

So you're checking for when that object collides with something

#

Does SpawnManager collide with anything

loud dragon
#

yes

undone stream
#

Hey sorry to bother i know youre in a conversation but does someone know how i can send data like variables from unity into python?
i tried it wiith chatgpt but somehow my gamw wont start if i use that so pleas help ;-;

polar acorn
#

Show the collider for it then

polar acorn
valid finch
loud dragon
polar acorn
# loud dragon

Okay, so does the object that SpawnManager collides with have the tag Target?

undone stream
loud dragon
#

yes

polar acorn
loud dragon
graceful flicker
#

So I am using dir.GetFiles("."); to get saved world data in a /Saves folder. Now I want to make it so world file is not saved into main /Saves folder but into a custom folder created in /Saves folder. Custom folder is created but how do I go into that folder and get my world data file?

polar acorn
ruby elk
#

The why is because thats very tough compared to just using python scripts in Unity. If you're using puthon because you don't know C# well @undone stream, you'll need to know C# anyway

#

*compared to just using C#

summer stump
# loud dragon

See that the tag says "Untagged" and only the NAME is Target

polar acorn
loud dragon
#

ok

swift crag
#

not "sending data into python"

polar acorn
loud dragon
undone stream
# swift crag Explain what you want to actually accomplish.

I got a Vr headset and im trying to make a 3rd party software so that i can play A "normal game" (not vr game), inside my VR headset,
im trying to accomplish that by sending the rotation of my player (headset in UNity) to a script on my PC that is then turning my mouse accordenly

polar acorn
# loud dragon

Okay, so, when an instance of this prefab makes contact with your SpawnManager, it should run that function

rich adder
loud dragon
#

ok

swift crag
graceful flicker
undone stream
valid finch
ruby elk
swift crag
#

sure. you would be having the python script start a websocket server, and have your Unity-based program connect to that server and send rotation data

#

I dunno how the latency would work out

graceful flicker
buoyant knot
#

Unity documentation says “Rigidbody2d.MovePosition is intended for use with kinematic rigidbodies.” But… what if I want to move a dynamic RB?

languid spire
graceful flicker
#

Because every save has different save folder name

undone stream
polar acorn
polar acorn
rich adder
undone stream
buoyant knot
ruby elk
#

I agree. This is not my expertise so I can't help much here.

valid finch
undone stream
ruby elk
#

I did

buoyant knot
#

i hope what I am going for makes sense

#

My player is moved around primarily by forces. But if he is on a moving block, I want the block to transfer any of its motion to my player (but I can’t use friction).

valid finch
#

@navarone is netcode for gameobjects good to use? for a 1 vs 1 online situation?

polar acorn
# buoyant knot In my case, I have my rigidbody moving in the reference frame of another object....

So, if your intention is to actually teleport the object, you'd want to set Rigidbody.position. MovePosition is for when you want to set a destination and respect all the physics behind it like collisions and whatnot which can very quickly cause some major jank with a dynamic rigidbody. If you want your dynamic rigidbody to just go to a place, you can set the position of it similar to how you can to a transform, and while it won't calculate physics along the way, it'll still actually move the rigidbody to the target location right away instead of lagging behind by one timestep

buoyant knot
#

that is what I have been doing, but I am getting collision jank, because I can be translating my RB’s collider into another collider

#

idk i wish there were like a joint2D that would just transfer it like a force

#

but all the joint2D I try also block the rigidbody’s own AddForce commands to move it

ruby elk
rich adder
valid finch
# ruby elk Yes you can find some pretty good tutorials online

Alright thank you. From where I am at now.. I have player movement, a play selection system, and receivers run the routes based on the play selected using some waypoints. Lots of just other basic scene setup. I don't think I am too far in to start planning for it

ruby elk
#

Yeah definitely start the netcode now because there a few implementations you’ll need

celest ravine
#

I am not sure if i am supposed to ask this in this channel, but basically I have a game where I have a sprite (square) and I have tried to import a .png of a square but now the square is way bigger, how do i make it so that the png i am trying to import is exactly 1*1 units big?

valid finch
#

Ok, just happy I asked about this today.. I just had a feeling.. I should be planning for this now.

rich adder
#

also fix your PPU size @celest ravine

celest ravine
rich adder
celest ravine
rich adder
#

right

celest ravine
valid finch
#

Make sure you keep your objects at the same ppu and plan around that size

buoyant knot
#

Does acceleration in unity just work like velocityNext = velocityOld + acceleration * Time.deltaTime?

swift crag
#

that would be valid, yes

#

acceleration is a change in velocity over time

#

like how velocity is a change in position over time

buoyant knot
#

i have to ask because classical physics only apply if you make it apply

#

I’m thinking about making a kind of different rigidbody API

#

let me know if this sounds dumb;

  1. Make singleton class with a list of all rigidbodies in scene that I need for calculations. This singleton class keeps a record of current position, previous position, defacto current velocity, desired MovePosition, and totalForce.
  2. Give rigidbodys extension methods that are used instead of MovePosition or AddForce, that only go tell that singleton to update values.
#

Script execution order:

  1. Singleton log: go through all rigidbodies and create new logs (velocity = old position - new position….), totalForce = 0….
  2. All my scripts do their thing, adding forces etc to singleton
  3. Right before physics calculation, singleton class (or some other helper class) goes in, and combines all the MovePositions etc to a covesive final result.
#

Good/bad? Pointless? Ideas?

swift crag
#

I don't see what the point is.

#

It sounds like you're just recreating AddForce

buoyant knot
#

So let’s say I have a player on a dynamic block that is on a kinematic platform moved by a kinematic motor moved by MovePosition.

swift crag
#

ah, you need to manage frames of reference

buoyant knot
#

exactly

#

so if multiple items down the line call MovePosition, it doesn’t work

#

because MovePosition commands overwrite each other, and only get executed in physics step

#

transform parenting doesn’t work… because idfk why

swift crag
#

because parenting something means its transform is getting messed with by something other than the physics system

buoyant knot
#

apparently having a dynamic rigidbody on a kinematic moving platform was not a common situation during unity development

buoyant knot
cosmic dagger
buoyant knot
#

even a joint. I would take a Joint tbh that moves an item, while letting it move freely

buoyant knot
#

so if the platform moves +2x, and the block moves with a force for +1x velocity, it can just get transferred to the player on the block on the platform

#

idk why this is so hard to do

valid finch
#

@rich adder so if I build a game that does local multiplayer.. would I need to do a complete overhaul of the code in order to make it online multiplayer. Because all of this netcode stuff is something I will need to learn to use, but I was just wondering if for testing purposes to get the base game working it would be ok local? Or is that going to be just way too much work to convert into online also in the future??

#

or anyone that has input on my question

cosmic dagger
# buoyant knot correct

that's similar to an update dispatcher i use to put MonoBehaviours in a separate list for FixedUpdate, Update, and LatUpdate and run those in their respective methods . . .

buoyant knot
#

i’m just sad that this feels so basic, yet so difficult

ashen ferry
valid finch
#

I was gonna make couch co-op for testing. I feel like the code I use for that would translate fairly well into lan and online.. it is just hurting my brain a bit. Trying to understand my next step you know

valid finch
valid finch
# rich adder LAN or Online will be the same

I guess I am just at a little roadblock, because I have never done the lan or online, and was thinking I could build it local and down the road turn that to online multiplayer

cosmic dagger
ashen ferry
#

yea at first could only connect in the same network but switching to proper multiplayer was open port in my router and set ip address in my network manager lmao

swift sedge
#

You should really use something like Relay

#

So you have a server the clients connect to instead of flooding their routers with excessive traffic

buoyant knot
#

It’s basically a hierarchy, but for reference frames that aren’t actually parented to each other

ashen ferry
#

my game is not gonna be self hosted but one single server all clients connect to, its fundamentally limited game to about 100 players maximum on single server/map so ye

buoyant knot
#

what I’m struggling on is the final piece: The line of code that actually makes them move

valid finch
swift sedge
rich adder
valid finch
#

Yeah, I was going to build it that way at first for testing..

rich adder
#

Couch Multiplayer is more in line with singleplayer than Lan

#

or Online

ashen ferry
valid finch
#

So i'd be screwed if I did it that way?

rich adder
#

No but you'll notice sending info between clients is very different than working on the same session

naive lion
#

idek where to ask about this but my camera just isnt doing anything
am i being really stupid?

valid finch
#

It's just frustrating to have my progress come to an abrupt stop.. cuz I am feeling the flow, but if I have to learn this stuff now, it's gonna be a big slowdown

buoyant knot
#

It just feels like I don’t have tools that work to sync their movement.
-MovePosition requests overwrite each other.
-Moving transforms makes janky collision
-I can’t just add force to a target position
-Joint2D either don’t sync motion OR block the child itself from moving with its own scripts
-Parenting transforms just doesn’t work
-Physics scenes don’t seem scaleable for this
I’m just so frustrated

swift sedge
valid finch
#

No same playstation. 2 controllers type of thing

swift sedge
#

Ohhhhh

valid finch
#

But I want that and in the future to add in LAN and online

swift sedge
#

Then you can use local device IP

valid finch
#

I was just hoping I could translate it down the road

rich adder
#

could start now looking into what you have to port over

valid finch
#

but I was worried I would run into major issues if I didn't plan for it now.

#

Figured multiplayer is multiplayer, but I am naive

rich adder
#

make a separate project and play around with just network package

#

you won't know for sure until you dive into it

valid finch
#

Whatever the player 2 controller does seperate it from the player 1 controller

rich adder
#

aint even about the controls

#

its sync 2 or more sessions of the same game

valid finch
#

and then have the game manager and stuff be shared

rich adder
#

so if 4 people playe your game, your scene is running 4 times. at different rates, so sync info between that is the challange

valid finch
#

Sorry, i'm not a complete moron.. despite how I sound right now lol... I am just overwhelmed with the revelation that I can't really progress until I understand something I wasn't planning on learning until a ways down the road you know?

#

Feeling like a deer in headlights right now lol..

swift crag
#

Multiplayer is all about maintaining consistency. You can no longer rely on everything happening in a specific order.

#

It's a lot to think about.

rich adder
#

Im not saying you are, its something you have to try out before you know what you need to port over from your current project

barren vapor
#

Is there a way to upload an image in playmode using a button? (Like the "+" button on discord. To upload an attachment)

valid finch
#

Yeah, using indexes for a lot of stuff, and set up my script load orders

ashen ferry
#

what genre will be ur game btw?

valid finch
#

its a 2D american football game

#

in the style of Tecmo Super Bowl

buoyant knot
#

idk, but maybe you should be using a command pattern?

buoyant knot
#

like, before any scripts execute, go get every player’s controller inputs for the frame, then use them.

#

this probably sounds naive, but that is my first thought

rich adder
barren vapor
buoyant knot
#

idk, maybe InputSystem already does that?

swift crag
barren vapor
valid finch
#

I feel like it is going to be a ton of trial in error. Right now I am racking my brain on a physics equation. It's the only one I will need for my game.

But when the qb passes the ball (has a pass speed) and the receiver is running a route along the x and y axis. at a speed.. I need to calculate where a straight line would need to be drawn to make the ball and the receiver hit each other in stride.

its distance + velocity (time) something along those lines

buoyant knot
#

oh, is that all?

#

oh, you’ll need calculus for that btw

rich adder
barren vapor
swift crag
#

I need to figure that one out

#

it's important for things like shooting at a player in a vaguely threatening manner

buoyant knot
#

you need some math help for your pass?

swift crag
#

oh dear god I googled "leading target math" and got this site

#

this is amazing

#

there's your answer. job's done!

barren vapor
ashen ferry
valid finch
verbal dome
valid finch
#

Same.. I really didn't think to call it leading a target.. which is literally what it is

ashen ferry
swift crag
#

i'm struggling to find a good resource for this, somehow

buoyant knot
# valid finch Same.. I really didn't think to call it leading a target.. which is literally wh...

Here, I show you how to make AI of different complexity for shooting at a player. All the way from 6 nodon AI to 150 nodon AI, I've got you covered, fam.

Level featured in the video: G-002-DXP-XXF
Sample code for AI turrets: G-003-P0N-667

0:00 Intro
1:10 Basic AI
4:35 Medium level AI
8:57 Jump hard
10:00 Let's go even further beyond
10:55 Comb...

▶ Play video
#

I did something like that in game builder garage, which has extremely shitty ability to do math/equations

#

i do have some useful approximations also in that vid

tame thorn
#

I have the main camera separate from the player, so when my camera moves vertically, the sword doesnt stay in the middle of the screen
how can i make it follow the vertical movement of the camera?

public class SwordController : MonoBehaviour
{
    public Transform swordCursor;
    public Vector3 defaultPosition;
    public Quaternion defaultRotation;
    public float rotationSpeed = 10.0f;

    void Start()
    {
        defaultPosition = transform.localPosition;
        defaultRotation = transform.localRotation;
    }

    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            if (swordCursor != null)
            {
                //Point towards SwordCursor Object
                Quaternion targetRotation = Quaternion.LookRotation(swordCursor.position - transform.position);
                transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
            }
        }
        else
        {
            // Smoothly move back to default position and rotation
            transform.localPosition = Vector3.Lerp(transform.localPosition, defaultPosition, rotationSpeed * Time.deltaTime);
            transform.localRotation = Quaternion.Slerp(transform.localRotation, defaultRotation, rotationSpeed * Time.deltaTime);
        }
    }
}
swift crag
#

lemme think for a sec...

valid finch
swift crag
#

you're basically solving a system of two equations

#

your choice of angle determines how quickly ∆x and ∆y change, and you want both to wind up being zero at the same time

valid finch
#

@buoyant knot OH shitt it's your video too. Thank you. I always was awful at math.

swift crag
#

the annoying part is that those values are both going to depend on t

buoyant knot
#

the youtube vid I sent has the answer, I’m pretty sure

tame thorn
verbal dome
#

So you look up and the sword stays in place instead of following the camera?

valid finch
tame thorn
valid finch
#

I don't know. I am gonna watch the rest of your video @buoyant knot because that projectile is leading the character

#

Thank you for sharing that

verbal dome
buoyant knot
#

sure

#

there are a few approximated versions as well, which aren’t perfect, but a lot better

valid finch
#

Stormtrooper AI lol

modern smelt
#

Hello guyz , i have some logic problem with TimeTickSystem. I want a code that exxecute three time in a row , so i'm a doing a for loop to make it go , but he litteraly just sprint in the for loop while counting only to twenty. Any advise ?

tame thorn
verbal dome
#

Or whatever you like

modern smelt
modern smelt
#

so i'm doing a loop for executing the void that instantiate with parameters of timer

valid finch
#

every 20 seconds?

modern smelt
#

every 20 ticks*

modern smelt
#

but he just sprint the loop then count

modern smelt
verbal dome
#

Some info missing here, not sure whats going on

modern smelt
#

sorry xD i'm using a tick counting , each tick add 1 to a variable , and at 20 , it make start a fonction

#

but i dont understand why does it skip each loop , then start counting

#

how is it possible for a code to run only after the end of the loop ?

verbal dome
#

You showed like 2 lines of code so Im still not sure whats up

modern smelt
rich adder
eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

verbal dome
verbal dome
# modern smelt

You should reset buildTick to 0 when 20 is reached, right?

verbal dome
#

OR, check it like if(buildTick % 20 == 0)

modern smelt
#

feeling stupid if this is the answer

valid finch
buoyant knot
#

that is the exact calculation. I could not do it in game builder garage because that engine is suck at math. But this would not be hard for you to do in unity, assuming I didn’t fuck it up

modern smelt
buoyant knot
#

note; Time of flight can give a nonsensical result if the pass speed is slower than the receiver’s run speed

verbal dome
buoyant knot
#

and I’m pretty sure the +/- is going to have only one of those two numbers being positive. so you’d ignore the negative time

valid finch
#

I appreciate your help very much

queen adder
#

Wondering how i can set my player to rotate with my mouse yet move the same way as i coded it

valid finch
valid finch
#

Oh and also, I'm gonna have to flip the calculation a bit on the x axis when the player is traveling the other direction it seems

queen adder
verbal dome
#

Also what kinda game? 2D topdown, platformer?

buoyant knot
#

the solution is complex (imaginary) time, which makes no sense

queen adder
buoyant knot
#

i would honestly evaluate the + and - versions of that equation. Assert that exactly one is positive. Then use the positive one, and continue with that time.

verbal dome
valid finch
buoyant knot
#

I have a PhD in chemistry, but this is just highschool math

valid finch
#

I skipped my math classes.

#

i went up to trig

buoyant knot
#

not a smart move lol

valid finch
#

yeah I am seeing that now 20 years later

#

brutal

verbal dome
#

Something like moveDirection = Quaternion.Euler(0, lookAngleY, 0) * moveDirection @queen adder
Or just rotate orientation I guess

queen adder
verbal dome
#

Probably movement since it doesnt affect camera really

#

I bet there are tons of tutorials that solve this though

#

Its basic 3rd person controls

valid finch
# buoyant knot not a smart move lol

Does the equation you send me account for the fact that different players can have different throwing velocities. I don't want the throw velocity to be based upon any factor other than what it is set at for the player's stat. If that makes sense. I am looking over the equation you sent and seeing what variables I have and what I need to create

buoyant knot
#

it is a function of whatever throw velocity you plug in

frail adder
#

is it better to use rb.velocity or rb.addForce for horizontal movement when creating a platformer?

buoyant knot
#

I would make a function: CalculateThrowVelVector(Vector3 receiverPosition, Vector3 throwerPosition, Vector3 receiverVelocity, float throwSpeed)

valid finch
#

Ok, thank you. I was looking at the final line you wrote

#

Was just trying to understand what that was for. Since the throw speed was already defined.

buoyant knot
#

Some of the other variables like angle, and (vector between thrower and receiver), and distance etc can be calculated from just those variables

#

you have throw speed. you need throw velocity, which has direction

valid finch
#

Ok, I wasn't sure, because I am not using actual physics in my game. This is just for the animation of the ball sprite to travel

buoyant knot
#

ie you know how fast the ball moves, but not where to throw it

valid finch
#

The ball won't be bouncing or dealin with gravity it is all done through animation

buoyant knot
#

yeah, this assumes none of that

#

this would be substantially more complex if you add gravity or anything to the mix

valid finch
#

Speed + direction is velocity. I forgot that speed and velocity weren't interchangable

buoyant knot
#

yeah. if you have that function, you can use it for any such case. plug in different throw speeds etc

#

that way you only code once

valid finch
#

Makes a lot more sense now. Thank you very much for your help.

buoyant knot
#

sure. also I think I used Vq and Vp interchangably for speed of QB and pass. They should both be speed of pass

dry tendon
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Pipes : MonoBehaviour
{
    void Update()
    {
        if (PipesController.Instance.canSpawnPipes == true)
        {
            transform.Translate(Vector3.left * Time.deltaTime * PipesController.Instance.speed);

            // Destruye el objeto si toca el lado izquierdo de la pantalla
            if (transform.position.x <= -Screen.width / 2)
            {
                Invoke("OnPipeTouchedLeftSide", 0);
            }
        }
    }

    private void OnPipeTouchedLeftSide()
    {
        Debug.Log("holaholaholaholaholaholaholahola");
    }
}
``` Does someone know why the debug low is not working? It is suppose to be printed when the object that contains the script collides with left side of the screan
valid finch
#

Maybe the player isn't actually triggering that collider

#

Or else you would be getting that debug log

steel frigate
dry tendon
steel frigate
#

I think you would need to use the cam.ScreenToWorldPoint function on your camera.

steel frigate
dry tendon
steel frigate
#

You would need to add something like this @dry tendon

    [SerializeField]
    private Camera cam;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        Debug.Log(cam.ScreenToWorldPoint(new Vector3(Screen.width, 0)));
    }
#

Well not the Debug.Log ofcourse you would replace your Screen.width, with the cam.ScreenToWorldPoint based on the screen width.

dry tendon
#

oh, thanks, ill try

queen adder
#

Stupid question but how do i unlock this

#

I want to change the shader color

polar acorn
#

Give it a material instead of just using the default

cosmic dagger
dry tendon
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Pipes : MonoBehaviour
{
    void Update()
    {
        MovimientoTuberías();
    }

    private void MovimientoTuberías()
    {
        if (PipesController.Instance.canSpawnPipes == true)
        {
            transform.Translate(Vector3.left * Time.deltaTime * PipesController.Instance.speed);
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "PipesDestroyPoint")
        {
            print("adiooooooss");
            Destroy(gameObject);
        }
    }
}
```Does someone know why print is not being executing?
polar acorn
dry tendon
#

@polar acorn all that is done

ashen ferry
#

bro its static

polar acorn
# dry tendon

This is a static rigidbody, so it's not moving. If the other object were dynamic and moving into it, it'd work

#

but a static rigidbody will not send collision messages

#

since it doesn't move

dry tendon
#

ooohh

#

thanks

#

it worked

ashen ferry
#

dont procceed to add rigidbodies for all the pipes tho use only one on the bird itself kekW

buoyant knot
#

i have rigidbody 2d in dynamic mode, where I need to translate them, and apply normal dynamic physics after. So my idea is; Set them all to kinematic mode, MovePosition to where I need, Physics2D.Simulate(0) so they move while respecting collisions without screwing with time-dependent code, then set back to dynamic mode.

#

Q: Would this work?

#

oh but the kinematic RBs wouldn’t push other things that should be dynamic…

#

!code

eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

noble rover
#

Oh apologies

royal ledge
#

While using the unity input manager system and the ”new input system” i have 4 different players with their own player input component so they are controlled by one gamepad each, whats the approach on making a UI system which is shared between them all?

royal ledge
#

@wintry quarry In that scenario each player has their own ui system

wintry quarry
#

you'd have to explain what kind of ui system you want

royal ledge
#

Like a menu that everyone can control

wintry quarry
#

that's vague

#

there are many ways to make "a menu that everyone can control"

#

for example there's Super Smash Bros' characte selection screen

royal ledge
#

Sorry i will try to be more specific, imagine a player presses start: A pause menu appears, with options up to down. The first option is selected. If player 1 presses down the selected option becomes the second option, if player 2 then presses up the first option will be selected again. They all share the same menu, and the same ”pointer”

wintry quarry
#

In this case you can use a regular event system and just write a custom input module that accepts inputs from any of your players

#

should be relatively straightforward

royal ledge
#

Aye thanks, all i needed was a point in the right direction, appreciate it

buoyant knot
#

would anyone know how MovePosition works on dynamic RBs? Does it ignore the request? Or does it actually try to move

naive lion
#

Hey really beginner question here
Im making a blink (tp) mechanic
Should I do this seperate to the controller for modularity or integrate it into the movement

frosty hound
#

If you have no intention of using it modularly outside of the player, then just integrate it.

naive lion
#

Awesome
Wasnt sure if either way it is better practice to do it seperate

buoyant knot
#

I am almost always in favor of separating

#

you might realize it's pretty simple to reuse the behaviour, or your original script gets huge (and later becomes messy)

sudden sand
#

I'm having a really hard time trying to edit the values of an object that I instantiate because it keeps changing the value of the prefab instead. I try to set the prefab to a gameObject in start() but I can't access it in any of my other methods, can someone please explain how this system works?

untold bobcat
#

How do you get a component with the type of a specific interface?

#

This doesn't give me any errors, but it also just returns null:
spellType = GetComponent<ISpellType>();

summer stump
#

Now, the start method only runs when it is actually active in the scene, so that should not modify the prefab unless you explicitly tell it to

#

You may wanna show the code so we can understand what's going on better

eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

swift crag
broken anvil
#

**heya how do i put two .GetComponent in one instantiate line?

swift crag
#

You may be looking at the wrong object

sudden sand
untold bobcat
swift crag
#

does this code ever actually run?

#

share your script

untold bobcat
untold bobcat
swift crag
#

!code

eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

untold bobcat
#

The damage spell script inherits from the interface im trying to get

swift crag
#

okay, that sounds fine. are there any errors in your console that aren't caused by this thing being null?

untold bobcat
#

Nope

swift crag
#

maybe turn on Collapse and look at the first error

untold bobcat
#

No errors at all

swift crag
#

ah, you check if it's null later before using it

untold bobcat
#

I'm 100% sure that the GetComponent line is the one returning null though

swift crag
#

You should log it.

#

what if the raycast is failing?

#

you can only be 100% sure when there is an unconditionally executed line of code that tells you that it's null

#

right now the only way you can tell is if a raycast hits a damageable object

untold bobcat
#

And nothing showed up in the console line

swift crag
#

sanity check by logging the result of GetComponent<DamageSpell>() as well

untold bobcat
#

so weird

swift crag
#

show me the definition of DamageSpell

untold bobcat
#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Spells
{
public class DamageSpell : MonoBehaviour
{
public void castSpell(GameObject particles, Vector3 targetPos)
{
Instantiate(particles, targetPos, new Quaternion());
}
}
}

swift crag
#

That does not implement that interface.

untold bobcat
#

does it have to???

swift crag
#

It doesn't matter if you happen to have all of the methods with the right names.

buoyant knot
#

what interface

swift crag
#

Just add the interface to the class definition

#

DamageSpell : MonoBehaviour, IWhatever

sudden sand
# summer stump A prefab is an asset file with the extension .prefab Instantiating one uses that...

start() {
//this below is copied twice up
GameObject HealthBar3Obj = Instantiate(HealthBar3, new Vector2(700, 450), Quaternion.identity) as GameObject;
HealthBar3Obj.transform.SetParent(CanvasObj.transform, false);
}

public GameObject getHealthBar(int playerNum)
{
Debug.Log("return health bar");
if (playerNum == 1)
return HealthBar1Obj;
if (playerNum == 2)
return HealthBar2Obj;
else
return HealthBar3Obj;
}

buoyant knot
#

maybe a little explanation about how interfaces work is in order

buoyant knot
#

you know how inheritance works?

sudden sand
untold bobcat
#

Ah it workie now. THanks Fen

summer stump
#

Declare the variable in the class

buoyant knot
#

just making sure you understand how it works in general, Vevy. Do you understand interfaces?

untold bobcat
#

Ill look into it more. THanks yall

buoyant knot
#

ok, do you know how inheritance works?

#

and how a class can only inherit from ONE other class in C#?

untold bobcat
buoyant knot
#

interfaces are like a way around that

#

do you know how abstract methods work?

#

where you are forced to override in a child class?

untold bobcat
buoyant knot
#

ok, an interface is like an abstract class, where every method is public abstract

#

AND then you are allowed to multiple inherit with them

untold bobcat
#

Yeah Im aware of all that

buoyant knot
#

most interfaces have like 1-4 methods tops

untold bobcat
#

Im not sure how I made tha tmistake lol

swift crag
#

see, if we only had typeclasses...

untold bobcat
swift crag
#

haskell typeclasses just require that you've defined a set of methods that work with a specific type. the type never explicitly "implements" a typeclass

buoyant knot
#

interfaces are really useful when you have multiple classes that are pretty different, that all need to expose a similar method that does something similar

#

Example; I have an ISpawner, which is an interface that any sort of spawner needs to have. Specifically, methods like SomethingWeSpawnedDied, SomethingWeSpawnedDespawned, and TrySpawnSomething.
And you can slap that interface onto a spawnpoint, or a pipe from mario, or bill blaster, or whatever. The spawner class can be all sorts of different things.

#

But now the thing it spawns doesn’t care. It just looks for an ISpawner to report it died/despawned/etc

#

idk if this helps, or you already know all this

sudden sand
# summer stump It is locally scoped. That's why

When i declare it in the class and run the code it still edits the prefab:
In a different class it tries to call the healthBarObj but it errors with "object reference not set to an instance of an object"

public void takeDamage(float damage)
{
healthAmount -= damage;
"healthbarobj"().fillAmount = 0.5f;

}
untold bobcat
#

:)

slender nymph
sudden sand
swift crag
#

Do not try to "simplify" code you are sharing.

#

It will just obfuscate the problem.

#

There's a lot going on in that line.

#

Any one of those steps could be failing.

sudden sand
#

yeahh

summer stump
eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

slender nymph
#

there are 4 separate objects just on the left hand side of the assignment operator that could potentially be null

sudden sand
#

Ok I'll spit it up and try and do some debugging

swift crag
#

a little suggestion: you should have a Healthbar component that holds a reference to the image

#

GameManager should also just be a reference to GameManagerScript, not a game object

#

then you could write GameManager.GetHealthBar(playerNum).image.fillAmount = 0.5f;

#

still a mouthful, but better

#

you could also then give Healthbar a method to set its fill

#

this would be nice if you want to make the healthbar slowly go up or down

#

or wanted to show a number along with the bar

#

or many many other things

#
GameManager.GetHealthBar(playerNum).SetPercentage(0.5f);
#

this makes it very clear what the objective is

#

you're setting the healthbar's percentage to 50%

teal vale
#

Hi. Working on a First Person Beat-em-up and I'm having trouble with the item grabbing system. I followed a tutorial. Everything works perfectly. The only problem is when I go to attatch the GameObject to my camera, (interact/pickup) It scales depending on my camera's rotation

swift crag
#

Sounds like non-uniform scaling.

slender nymph
#

don't attach it to the camera

#

but also that

teal vale
#

I wish I could send a video, but it bypasses the file size limit

slender nymph
#

you can use something like a parent constraint to make your holder object follow the camera as if it were a child without actually being a child

swift crag
#

If an object's parent has a non-uniform scale, and the object rotates, it will get skewed as it rotates.

slender nymph
#

parent constraint . . .

teal vale
#

my script makes it so that when you interact within the collider range, it teleports the object to an empty

slender nymph
#

congrats. use a parent constraint so that "empty" gameobject acts like a child of the camera

sudden sand
# swift crag you're setting the healthbar's percentage to 50%

I'll try and do this, the problem I set for myself is that I have three characters that all have to have different health bars, I need to instantiate the healthbars to match the color of the character, but I need to set the parent of the healthbars to the canvas since they weren't working when I didn't... long story short, I need one code that can instantiate one canvas and three prefabs and it runs three seperate times because I have individual health managers for each of the plays... sorry if that doesn't make any sense, ive been working on this one code for a few days and its driving me a tad insane

swift crag
#

making a dedicated Healthbar class will also make your life easier

teal vale
#

also, I don't know what parent constraint is, so in order for me to be less of a nuisance to you, you might have to explain instead of expecting me to know everything

swift crag
#

the healthbar can even reference a health manager

sudden sand
swift crag
#

and then update all by itself

swift crag
swift crag
#

(but also consider googling, yes)

slender nymph
#

it's a component

sudden sand
teal vale
swift crag
teal vale
#

I thought it would be some sort of an overcomplicated type of method in code or smth.

slender nymph
#

next time you see something suggested and you don't know what it is, try googling it first instead of complaining that i didn't immediately explain it to you

teal vale
#

Sorry about that. My first experience with asking this server for help was unpleasant so I feel like everyone is yelling at me even though sometimes they aren't

frozen stream
#

Nevermind I'll move my question to #🎥┃cinemachine , unless that counts as reposting a question?

slender nymph
#

if you move your question to another channel be sure to delete it from the original channel

frozen stream
#

okay

#

@slender nymph would updating the m axis' on cinemachine cameras through code, be a coding channel question or a cinemachine channel question?

naive lion