#archived-code-general

1 messages · Page 236 of 1

storm thorn
#

https://youtu.be/1ZYRsHUzHyQ?si=ZkR8mKrH0Rb2YKWA

Hello! I have firebase authentication, should this reward system be connected on firebase? or can I do this tutorial on its own? like when the users login, will they be able to use this reward system?

#madewithunity #unity3d #unity #indiegame #gamedevelopment #gamedev

How to make a daily reward system easily in Unity

☴ Assets :
https://github.com/herbou/Unity_DailyRewardSystem

🎵Music :
https://www.bensound.com/

🌐Follow Me :
Facebook : https://www.facebook.com/h.herbou
Instagram : https://www.instagram.com/hamza_herbou/
Behance : https:...

▶ Play video
crude elm
#

Is this possible to set and add a Full Screen Pass Renderer Feature to the Universal Render data with code instead of an Editor menu?

royal temple
#

Hello guys, I'm using a Ray from my Camera and the Ray seems off by a fixed offset to the right, any pointer as to what could be wrong please ?

Here's the code (simplified):

var hits = new RaycastHit[100];
var ray = GameManager.Instance.MainCamera.ItemInvestigationCamera.ScreenPointToRay(Input.mousePosition);
const float castDistance = 100;
int hitCount = Physics.RaycastNonAlloc(ray, hits, castDistance);
float closestDistance = float.MaxValue; // TODO: Make this distance the current Room's AABB's diagonal
Interactable closestInteractable = null;
            
#if UNITY_EDITOR
UnityEngine.Debug.DrawRay(ray.origin, ray.direction * castDistance, Color.red, 2.0f);
#endif

And yes, the Camera being used is the one Camera which renders the Item I'm trying to click using that Ray, so it's coherent

leaden ice
#

what makes you think it's off?

#

(side note - the way you are using RaycastNonAlloc with a new array each time is not ideal but that's an optimization issue for later)

royal temple
#

I draw it, and there is a clear offset to the right. If I click, let's say, about 70% to the right of my screen (middle vertically), the ray that I draw will be outside of camera frustum

leaden ice
#

given that it's coming from the camera

royal temple
#

I'm looking at it in Editor

#

No in game view

leaden ice
#

in scene view?

royal temple
#

Yes, scene view*

leaden ice
#

Ok can you show a screenshot?

royal temple
#

You'd be right in saying it's invisible from Game View

#

I can't post screenshot as the game I'm working on is under strict NDA 😦 but I have looked at every angle and it's offset

leaden ice
#

My guess is you have tool handle pivot set to Center instead of Pivot perhaps

#

so you're mistaken about the camera's actual position

royal temple
#

What do you mean by "Tool handle pivot" ?

leaden ice
#

the one on the left here

royal temple
#

Because it doesn't seem to be a Scene View specific problem. The actual behavior doesn't work either (as in, my object doesn't get clicked)

#

It's under the mouse when I click and it doesn't react to the click, it's not in the list of Hits when I break into the code, and the visual debug shows me it's off, so this all seems very coherent

#

(but bugged)

leaden ice
#

What kiond of colldier does it have?

#

etc

royal temple
#

A simple BoxCollider

#

It's just a gameobject with a BoxCollider and a component script to help me detect the right kind of object

#

Admittedly not the most optimized choice either but works well enough

leaden ice
#

From what you've shown me here so far I would expect it to work fine

royal temple
#

All right, I'll keep digging. thank you for trying

ivory pasture
#

do collider2d s inside canvas interact with those outside?

hidden flicker
#

Why doesn't the player move along with moving objects that it's on top of

#

It's a purely physics based player

#

Non-kinematic

rigid island
spring creek
polar marten
polar marten
#

you're using a ray from a camera, but i don't know what "my" camera means

#

also, this isn't the code, it's simplified, so there could be a lot of problems

polar marten
crude elm
swift falcon
#

How the project settings works? I want to create my own settings. For instance, the physics tab. You can access the Physics Settings by Physics class which is not a static class. Then where it is getting the settings from? I currently saving my settings to the ProjectSettings Folder as a JSON file maybe that is the way?
I see there is no PhysicsSettings.asset inside ProjectSettings folder

swift falcon
#

Hm? PlayerSettings?

rigid island
knotty sun
swift falcon
#

I got confused when i saw there is no PhysicsSettings file. I wonder where it gets saved. I have Physics2DSettings.asset even the game itself 3D but not PhysicsSettings.asset

#

Also how it loads? I guess its should be done by an instance? But there is no instance at their script wo... ._.

arctic lintel
#

my musicNSounds value is correctly set but my dropdown values aren't... even if I put a fixed value like 95, the value in the dropdown isn't changed. here's my bad code (optimization is for later rn I need a working code) and here's how I call it...all variables are correctly assigned

#

and if I put in update, the value is correctly set but I only needs at start... and I tried with a bool alreadyLoaded in the update and it wasn't working

leaden ice
#

You should also probably be using SetValueWithoutNotify

arctic lintel
#

I checked but no, nothing else is touching my dropdowns

polar marten
#

like why do you need to add this programmatically? is the goal to do something at runtime? or as an editor feature?

leaden ice
polar marten
#

if it's for editor scripting, use reflection

arctic lintel
#

I changed every ".value =" to the func you gave me but still nothing 🥲

leaden ice
#

Maybe multiple places

arctic lintel
#

in the Start()

leaden ice
#

Of what

arctic lintel
#

of my same script attached to an empty

leaden ice
#

Add more logs

#

Before and after this code for example

#

Make sure the values being read from the file are correct for example

#

It's also possible your UI element references are incorrect

arctic lintel
leaden ice
#

Lots more debugging and checking assumptions to do

arctic lintel
#

and still works

crude elm
hidden flicker
#

Basically something which is only affected by its own interal forces, and not external forces

swift falcon
# swift falcon I got confused when i saw there is no PhysicsSettings file. I wonder where it ge...

It seems they called the PhysicsSettings.asset as DynamicsManager.asset. But anybody can help me how this Serialized ScriptableObject gets handled?
I want to create my own settings that can be accessible like Physics class. Lets say the settings i create is named as "CustomAppSettings". How would the CustomAppSettings.asset in ProjectSettings gets loaded?
I am thinking to use an instance right now.

spring creek
#

You can try parenting to the plaform

#

Or adding the platforms movement to the players while some spatial query tells you the player is on it (same thing as grounding, but you search a tag or script that tells you it is a platform)

polar marten
#

for example, a canvas image

#

another one is a volume

prime quarry
#

Asriela — Today at 20:39
I was making an alarm struct to give me easy to use timer functionality in unity, but i get an error saying i cannot modify a collection im assuming in a foreach but I cant figure out how to do a for with a dictionary

fervent furnace
#

ok
the foreach loop is actually some codes like:

while(collection.HaveNext()){
  var c=collection.Current;
}
#

and you are modifing the c, a value type and a copy of the value in collection

somber tapir
fervent furnace
#

oh i misread, you are modifing the collection directly

#

it is prohibited in foreach since it causes iterator fails

prime quarry
somber tapir
fervent furnace
#

you cant use for loop to iterate dictionary (though you can use reflection to get the entries array)

leaden ice
#

I would probably set this up so it's a dicitonary of alarms to the "end time" for the alarm, rather than constantly modfiying them though

#

then you don't have to worry about modifications at all

simple egret
leaden ice
#

instead of decrementing all the timers in a loop

#

you increment ONE external timer variable

#

and check if the time in the dictionary is <= it

prime quarry
simple egret
#

Oh god

crude elm
# polar marten another one is a volume

Yes, but isn't Fullscreen Shader suppose to cover this as well? From what I've read it allows to fade out, make transition and apply effect over the camera. And in URP it requires to add a feature per shaders or swap materials. However, I wasn't aware that Volume can black out a screen.

simple egret
#

Cramming the ones you couldn't categorize in a single enum, bad idea lol

#

enum AlarmType - Even if it contains just 2 values it's still worth it to make a separate one

somber tapir
# prime quarry why is that

It makes things cleaner and more extendable. What if you want to add something to your alarm, like listeners. You'd have to add a new Dict for every new variable and they are not linked with each other. Or if you want to have different types of alarms, maybe one that triggers multiple times, you'd have to use multiple if statements.

polar marten
#

with a black rectangle in it

#

all the alternatives are worse

#

why author a shader? what is the purpose of all this nonsense

#

@crude elm i suppose you're not sure why you got into that rabbit hole but it's okay. make a canvas. what you are asking to do otherwise is not supported.

prime quarry
prime quarry
#

how would i set up key value pairs with objects

strange gate
#

Hello can someone explain how to fix this error?

prime quarry
#

i am realizing how convenient game makers Map datastructure was, but obviously limmited if you wanted to do advanced stuff

spring creek
crude elm
leaden ice
prime quarry
strange gate
leaden ice
#

so when the timer gets to e.g. 5.032, timer #1 is done

#

it would just be a if (currentTime >= timer[key]) check

spring creek
#

You may want to take the !learn courses

tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

leaden ice
prime quarry
simple egret
#

No, because you popped the first one from the dictionary

#

It's essential to do that, once a timer is done, remove it from the collection

leaden ice
#

so e.g. that alarm would be at 12 seconds if it's currently 7 seconds and you want it to last 5 seconds

#

you can call them "alarms" really if you want to be more accurate with this paradigm

polar marten
prime quarry
#

the whole point is to be able to go: alarm.Start(Az.Timer.spawnInterval, spawnInterval, true); and now I have a looping timer - with the true argument saying it loops. (Adding looping now)

polar marten
#

i apologize because it is going to be hard to achieve anything in XR

prime quarry
#

so i can refer to specific alarms/timers and have them be created, started and set to looping or not all at once

crude elm
simple egret
#

Then for looping ones, once it reaches the set time, just add currentTime + interval to the timer and you're good to go

prime quarry
simple egret
#

The struct could contain a property of your enum type, so each one has its own alarm type

#

public AlarmType Type { get; } or something

prime quarry
#

so how would I find the struct with the correct enum type assuming im storing them in a list

#

oh id just have to iterate through them all

#

manually

simple egret
#

Why would you need to find a specific one yes?

#

Since you need to update them all at once, you can loop through the list unconditionally

prime quarry
#

so i can reference one

#

for example, if (alarm.Ended(performanceTimer)) {do performance heavy code}

simple egret
#

Riddle me this, what if there are 4 alarms of type performanceTimer that are finished when you call this function? What does it do?

prime quarry
#

well either I dont add multiple performance timers, unless i accidentally do that and even then i can just throw an exception if i try creating a new timer with an existing id (to ensure unique keys) but even if i dont do all that it will just find the first entry with that key and check its value

swift falcon
#

can anyone tell me how i can check if a function could be called in unity or if it throws an error. in c++ you just do if( function() ) but idk about c#

simple egret
strange gate
#

So I need to rename my class into my actual game gun?

simple egret
somber tapir
simple egret
tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

tardy moss
#

Is it legal for this discord if in unity learn I skip the basic c# specific stuff because Ive been using it for a couple of years I just need to learn the unity specific c# stuff ??

#

Like I know you could check my badges/progress if you wanted

spring creek
simple egret
#

Straight to jail

clear rampart
#

I have a problem. So basically i'm doing a clicker game and I have an upgrades class for every upgrade. The thing is I created a function for buying those upgrades that basically what it does is updating the values inside the class but I don't know how to make a generalized name for that class. For example
public void BuyUpgrade(UpgradesData upg)
{
upg.quantity += 1;

    Debug.Log("Purchase Done Successfully.");
}

so I don't know how to call that function and give it the name of an existing class.

I hope you undersatnd the problem

if I don't find a solution I will have to create a function to buy every upgrade.
That's what I'm trying to optimise

tardy moss
spring creek
#

It is a free course they can take on their own time.
When they have specific issues that show they understand the basics, that is a better use case for this discord

#

Do what you want from it. But if someone points you to it, it means that you are missing something crucial that the course explains.

Like what a class is

#

There are many other courses online too, you can use any you would like

somber tapir
prime quarry
#

So I have run into an issue in that structs cant be nullable

simple egret
lucid valley
quartz folio
#

Generally better to use the TryGet pattern though

strange gate
#

Im down

prime quarry
quartz folio
#

I don't know what that means

prime quarry
quartz folio
#

How do you know if alarm has a type if it's nullable?

#

You need to check alarm.HasValue and use alarm.Value

prime quarry
#

as in if(alarm.HasValue && alarm.type== typeLookingfor)

simple egret
#

The list shouldn't contain nullables

#

Only the local variable that might store (or not) the alarm it found

#

But I'd use the TryGet pattern, it's better for that very specific case

tardy moss
quartz folio
#

I don't think C# works like that with nullable structs in any version afaik

prime quarry
tardy moss
#

shrug I guess Ill never understand why int ?somevar; somevar?.ToString() is fine but not somevar?.Value and have to check .hasvalue every time

simple egret
#

what?

#

Like v?.ToString()? Well the compiler expands if to an if statement that does if (v.HasValue) v.Value.ToString()

#

So it works

tardy moss
#

No Im just pissed of that I have to check .hasvalue and != null every single time for a nullable

simple egret
#

No you don't have to

tardy moss
#

instead of just doing ?.Value just seems random things microsoft did to be annoying

simple egret
#

x?.Value is nonsensical since ?. already checks if there's a value for nullables, so ?. accesses the underlying type

somber nacelle
#

not only that, but the context of the issue is within an if statement. an expression using the null conditional operator (?.) evaluates to null if the object the operator is used on is null and you cannot just do if(null)

tardy moss
#

This is what I mean btw. I do know it's just it annoy me every single time especially that the struct is a value type and so is int:

simple egret
#

Because what's after ?. is a value of type SingleAlarm

#

You would be able to get the getupyou.... member if it was public, here

prime quarry
somber nacelle
tardy moss
#

ok lol it was just a mistake then 😄 I really thought for the last 10 minutes that MS had randomly decided it didnt work for structs but I turns out I just forgot the public

tardy moss
prime quarry
#

Comming from game maker studio to c# makes c# feel like an elderly person who constantly goes "HUH what did you sayy?? You got to speak up sonny and be specific!"

rancid void
leaden ice
rancid void
#

whats my mistake?

leaden ice
#

They may seem more tedious, but static typing is a godsend

leaden ice
rancid void
somber nacelle
#

basically either you never assigned GameManager.instance or this object does not have a TextMeshProUGUI component

leaden ice
# rancid void

either GameManager.instance is null or textMesh is null

#

figure out which one

somber nacelle
#

in fact, i would be very surprised if it has a TMP_Text, a Button and an Image component

rancid void
#

but textmeash is only for text right and i need a button

#

im a beginner

somber nacelle
#

sure, but does this one gameobject have all three of those components on it? or are they perhaps children of the object this component is attached to?

rancid void
somber nacelle
#

well there you go, it doesn't have a TextMeshProUGUI component

leaden ice
tardy moss
rancid void
leaden ice
#

It shows all of the components

#

there is no TextMeshProUGUI component there

#

your code is saying textMesh = GetComponent<TextMeshProUGUI>(); since no such component exists, it will simply return null

#

then when you try to use this null variable you get an error

#

Is that clear?

rancid void
#

yes

#

so i have to use image right?

#

because when i want add a textmesh it show this

wise pumice
somber nacelle
leaden ice
# prime quarry

You've clearly never worked on code other people have written!

rancid void
#

i look it up on youtube

prime quarry
leaden ice
leaden ice
#

and it tells you at compile time when you try to do something like accessing a method or variable that doesn't exist

prime quarry
#

In that u may know the history of what u have written but others dont

leaden ice
#

or try to pass an object of the wrong type into a method, etc.

#

We call this "type safety"

prime quarry
tardy moss
thick socket
#
public class DamagePopup : MonoBehaviour
{
    private TextMeshPro textMesh;

    private void Awake()
    {
        textMesh = GetComponent<TextMeshPro>();
    }
    public void Setup(int damageAmount)
    {
        textMesh.SetText(damageAmount.ToString());
    }

    //create a damagePopup
    public static DamagePopup Create(Vector3 position, int damageAmount)
    {
        Transform damagePopupTransform = Instantiate(GameManager.instance.pfDamagePopup.transform, position, Quaternion.identity);
        DamagePopup damagePopup = damagePopupTransform.GetComponent<DamagePopup>();
        damagePopup.Setup(damageAmount);

        return damagePopup; 
    }
}
#

as a "static" noob

#

why would you use static here?

#

dont fully understand why static is ever used tbh

somber nacelle
#

it doesn't touch anything in the instance so it doesn't need to be an instance member

thick socket
#

I dont quite follow what that means

simple egret
#

And it's more of a "factory method", it's made to create, set up, and return the object for you

#

It's accessible everywhere from anything

tardy moss
#

static keyword imply that you wont touch an instance of damagepopup. Following OOP principles any operations related to DamagePopup need to be in a DamagePopup class. But some operations don't need an instance of the class

#

so static here semantically says, this feature belongs to me but I dont need to get some data from myself or change myself to do it

leaden ice
# thick socket I dont quite follow what that means

The only difference between a static method and a non-static one is that non-static methods include an implicit "this" reference, which is the object you called the method on. when you say someObject.SomeMethod() you can imagine that you're actually calling a static function with someObject as the first parameter to it, which can be referenced inside the method as this.

If you don't need the this reference at all in the function, there's no need to include it, thus you can make it static

thick socket
#

hmmm, so with a "static" in this case

#

I can just do DamagePopup.Create

#

instead having to create a new DamagePopup and then call "create" after it?

lean sail
thick socket
tardy moss
#

I miss static variables inside method 😦

thick socket
#

Dont I need to the transform to "getcomponent" of the damagepopup?

somber nacelle
#

if you pass a DamagePopup type into Instantiate then it returns a reference to the instantiated DamagePopup component completely removing the need to use GetComponent

thick socket
#
DamagePopup damagePopup = Instantiate(GameManager.instance.pfDamagePopup, position, Quaternion.identity).GetComponent<DamagePopup>();
damagePopup.Setup(damageAmount);

return damagePopup;
#

just like this instad?

lean sail
somber nacelle
thick socket
#

it throws a "can't convert type"

somber nacelle
#

yes because you went and added .transform to it again

thick socket
#

oh interesting

#

I see that now thanks

#

for some reason I thought it had to have a Transform to be "Instantiated"

#

I if I wanted to make my own class that just Debuged.log 2x everytime I called it I would do this right?

#
public class DebugLog: MonoBehaviour {
public static void create2x(string message)
    {
        Debug.Log(message);
        Debug.Log(message);
    }
}
#

could just call

DebugLog.create2x("test");```
somber nacelle
#

it doesn't need to be a MonoBehaviour for that, but yes

thick socket
#

dang

#

this would have saved me so much time for years thanks!

#

always thought it was super annoying having to create an object to then call functions on it 😄

stable geyser
#

Hey all, trying to create broadsides style naval combat in my 2D game. Tried to find a tutorial to show me how to do this but can't find anything. User should be able to choose to fire out port or starboard sides with different keys. They can hold the fire button to "charge" their shot which affects the spread of the projectiles fired. Anybody know where I might find a tutorial on something like this?

#

Oh and I also need a visual indicator for the player of the charging step 😛

unkempt meadow
#

OK so why does controller crouch work the way it does? It reduces the collider inward, making your legs fall through the floor. I struggle to see the use of that

hard viper
#

Most shader tutorials don't seem quite right for this. does anyone have advice over how to do this?

#

example: I have a water shader, and lava shader, and both tiles could be on the same tilemap (or whatever), and I know I have water at positions A,B,C and lava at D,E,F, and I want to apply the water shader for A,B,C and lava shader for D,E,F. How would I even start to set this up?

arctic lintel
#

settings.keybindSystem.p1.forward is a dropdown that the default value is 68, I'm trying to change the value but it doesn't work
here's everything you need to help me...
btw, my menu with my dropdowns is not Active to hide the menu when not suppose to be seen but even when the menu is Active, and the dropdowns are visible... the value doesn't change...can anyone help me with that?

thick socket
#

Any chance yall could help me figure out what VS shortcuts he does here from 15:00->15:10?
There are quite a few and seems to save a lot of time but I can't figure out how to look them up(or what they might be called)

https://youtu.be/iD1_JczQcFY?si=0sXQTMvaA2PTaRUZ&t=900

simple egret
#

15:05 - Shift + Enter to add a line above. Or Ctrl + Enter. I don't remember.
15:09 - Ctrl + R twice to rename the identifier under the cursor, and update everywhere it's used.

  • This works across the whole project, so if you're renaming a variable that's public and used in 15 scripts, it'll do the rename in the 15 scripts.
  • When renaming a class, it will also rename the file for you.
kind cipher
#

This is a scene I haven't had to touch for months, but today, string split is misbehaving. This is the logic where it splits the string.

foreach (FsmString pair in customSessionProperties)
{
    Debug.Log(pair);
    string[] keyValue = pair.Value.Split(',');
    string key = keyValue[0];
    Debug.Log(keyValue[1]);
    string value = keyValue[1];
    SessionProperty property = value;
    properties.Add(key, property);
}```
#

here is the console log

#

its skipping over the word arena

#

in 8 months its never done this. why now?

simple egret
#

What says it's skipping it, you're not logging key nor keyValue[0]

hard viper
#

I would use the debugger to look into what is in these variables

kind cipher
hard viper
#

instead of using debug.Log

#

is there a simple way to make a shader that operates on a specific type of tile?

simple egret
thick socket
#
    private static int sortingOrder;
 public void Setup(int damageAmount, bool isCriticalHit)
    {
        sortingOrder++;
        textMesh.sortingOrder = sortingOrder;
    }```
#

am I going to run into issues where the sortingOrder int is being accessed twice at the same time

#

and thus both will be ex)10 and then the 3rd will be 12

#

not sure how unity might thread things

simple egret
#

Unless you multithread yourself, no code will be executing twice at the same time

thick socket
#

awesome thanks

#

didn't know you could really multithread yourself with unity

#

but I guess maybe Async could do that

spring creek
polar marten
spring creek
#

Dots is multiple things. Jobs, Entities, and the Burst Compiler

hard tapir
spring creek
simple egret
# thick socket good to know thanks

For completeness C# does provide methods for handling access from multiple threads in an atomic manner, which means the use is locked to the thread that is modifying the variable, to ensure nothing else is accessing it in the process.
For example, there's Interlocked.Increment() which is used to atomically increment a value

hard tapir
polar marten
hard tapir
#

How to make corners to be square ⬜ if segments count is 1. Currently it makes triangle. ```var u = 0f;
for (var c = 0; c < 4; c++)
{
// Create verts
var origin = _corners[c];
for (var i = 0; i < _cornerSegments + 1; i++)
{
// Calculate angle and direction
var angle = (float)i / _cornerSegments * Mathf.PI / 2f + Mathf.PI * 0.5f - Mathf.PI * c * 1.5f;
var direction = new Vector3(Mathf.Cos(-angle), Mathf.Sin(-angle), 0f);

    // Calculate vertex position for the inner corner
    vert.position = origin + direction * clampedCornerRadius;
    vert.uv0 = new Vector2(u, 0f);
    _verts.Add(vert);

    // Calculate vertex position for the outer corner (outline)
    vert.position = origin + direction * (clampedCornerRadius + _outlineWidth);
    vert.uv0 = new Vector2(u, 1f);
    _verts.Add(vert);

    // Fill center condition
    if (_fillCenter)
    {
        vert.position = rect.center;
        vert.uv0 = new Vector2(u, 0f);
        _verts.Add(vert);
    }

    // Increment u based on segment or edge length
    if (i < _cornerSegments)
        u += segmentLength / around;
    else
        u += edgeLengths[c] / around;
}

}

polar marten
unkempt meadow
polar marten
#

there are dedicated, free fps character controller assets that may be more useful though

#

are you trying to change the height over a period of time, or instantaneously?

unkempt meadow
#

Being a unity built-in feature, I struggle to see why the base couldn't be the point of origin, it doesn't make any sense otherwise

#

I have all the movements and controllers

#

I just never got around to reducing the collider while crouching; only playing the animations

#

over a short period of time

polar marten
#

you are overthinking this. in the editor, design the two collider shapes so that it looks right to you. then copy those settings

#

don't try to change the shape over time

hard tapir
red bramble
#

I've got a concept for making a lock-on system for my fixed-camera game that I'd like to run by somebody if they have the time.

I'm in the prototyping stage for it and I'm wondering if my thought process is going the correct way for this.

red bramble
leaden ice
thick socket
#

you didn't ask anything coding related

hard tapir
red bramble
rocky basalt
#

Hi. I have a situation where I'd like to pass a base class into a method and then cast it as an inherited class. This would not be done every frame - maybe every few seconds or so.

I remember reading some Unity docs about "boxing" and casting creating memory issues, but I'm a programming n00b.

Wondering if anyone could sanity check whether I should be concerned about casting such as "MyBaseClass class = MyBaseClass as MyInheretedClass" <--- I know that syntax might be wrong, i just wrote it from memory

simple egret
# rocky basalt Hi. I have a situation where I'd like to pass a base class into a method and the...

No there's no problem at all with casting. In fact casting does not modify the memory at all, it just does checks to ensure what you're casting to is the expected type. So it's pretty much nothing to worry about in terms of performance.
Boxing happens when there is a cast from a value type (a struct, for example int) to a reference type (eg. object). This forces memory to be reserved to store the int as object

rocky basalt
#

Every time I read some performance warnings in a doc, I mentally file away as "here be dragons" without necessarily understanding the exact reasoning/machinations behind the warning lol.

simple egret
#

And it's mostly never a performance problem unless you're doing the thing thousands of times per second.
As always, if there are performance issues use the profiler to locate the source and fix it

thick socket
#

I can do a pool of type GameObject right?

#

running into issues with trying to check a dictionary and it doesn't seem to want to be the same key

rocky basalt
thick socket
#

if I put a gameobject as a key

#

cloned it

#

would they both count as the same key?

rocky basalt
#

No, if you clone it, it has a different instanceID and all that. So it's a different key

thick socket
#

"rips out hair"

#

thanks

rocky basalt
#

Yeah it's easy to trip over value vs references when learning Dictionaries and such. If you use a reference type like GameObject as a key, it's checking for that particular instance

thick socket
#

RIP my pool 😦

#
public class BasicPooling : MonoBehaviour
{
    public Dictionary<GameObject, ObjectPool<GameObject>> BasicPool = new();
    [SerializeField] List<GameObject> items;
    public static BasicPooling instance;
rocky basalt
#

If you wanna feed the dictionary a key that represents a certain 'type' of object, there are other ways of doing it. For example, give every object type an integer that represents it. There are surely better ways too, I'm not an expert

thick socket
#

with any luck it will work like this now...

#

hurray 😄

thick socket
# rocky basalt I read the code you deleted before, there was a lot going on and I think you can...
public class BasicPooling : MonoBehaviour
{
    public Dictionary<BasicPoolEnum, ObjectPool<GameObject>> BasicPool = new();
    [SerializeField] List<EnumObject> items;
    public static BasicPooling instance;


    // Start is called before the first frame update
    void Awake()
    {
        instance = this;
        foreach (var item in items)
        {
            var tmpPool = new ObjectPool<GameObject>(() => CreatePooledItem(item.gameObject), TakeFromPool, ReturnToPool);
            BasicPool.Add(item.basicPoolEnum, tmpPool);
        }
    }
    void TakeFromPool(GameObject item)
    {
        item.gameObject.SetActive(true);
    }
    void ReturnToPool(GameObject item)
    {
        //Do Particle Explosion
        item.gameObject.SetActive(false);
    }
    GameObject CreatePooledItem(GameObject tmpItem)
    {
        var item = Instantiate(tmpItem);
        item.transform.SetParent(transform);
        return item;
    }
    public void Release(BasicPoolEnum basicPoolEnum, GameObject item)
    {
        BasicPool[basicPoolEnum].Release(item);
        Debug.Log("released");
    }
}
public enum BasicPoolEnum
{
    damagePopup=0
}

[Serializable]
public class EnumObject 
{
    public BasicPoolEnum basicPoolEnum;
    public GameObject gameObject;
}
thick socket
lean sail
rocky basalt
#

Dammit i still don't know how to make code look nice

lean sail
#

i wouldnt really do it based on ints unless this class also provides a lookup for object to int.

#

3 backticks and write cs after the first 3

rocky basalt
#
int objectOneID = 0;
int objectTwoID = 1;
List<int> myObjectIDs = new List<int>();

GameObject goToSpawn;
int amountToSpawn = 10;

public Dictionary<int, List<GameObject>> myPoolsDict = new Dictionary<int, List<GameObject>>();

private void Start()
{
    myObjectIDs.Add(objectOneID);
    myObjectIDs.Add(objectTwoID);

    PoolObjects(myObjectIDs);
}
void PoolObjects(List<int> listOfInts)
{
    foreach (int itemID in listOfInts)
    {
        List<GameObject> pooledObjects = new List<GameObject>();
        for (int i = 0; i < amountToSpawn; i++)
        {
            GameObject spawnedObj = Instantiate(goToSpawn);
            pooledObjects.Add(spawnedObj);
        }
        myPoolsDict.Add(itemID, pooledObjects);
    }
}
thick socket
lean sail
# rocky basalt ```cs int objectOneID = 0; int objectTwoID = 1; List<int> myObjectIDs = new List...

🤔 honestly this doesnt make a lot of sense, theres 1 goToSpawn but 2 object ID's which seemingly arent used to reference different objects. This would also be a nightmare to use, everytime you want to add to the pool you have to edit the code or open this file to see what the ID was.
https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/v2.2.0/Assets/Scripts/Infrastructure/NetworkObjectPool.cs
This is a good implementation, it was made for network objects in unity netcode but very very easy to swap to component based like I wrote above.

lean sail
rocky basalt
#

Just wanted to share the outline/principle quickly

polar marten
leaden ice
spring creek
thick socket
#

Oh cool thx, thought he just wrote "component" as a fill in for components

thick socket
rocky basalt
# leaden ice memory/performance issues are actually close to the least important factor you s...

Honestly I probably don't need to cast. I've been refactoring code the last few days and was going to use that 'thing' as a bit of a shortcut. But in simplied terms, Class C enables some 'modular' gameplay behavior where it can take in both ClassA or ClassB as building blocks. Just wanted to use one list instead of two. But, I could probably get rid of ClassB entirely since it kind represents clusters of ClassA. I'm aware none of that made sense

lean sail
shrewd mulch
#

does any one know how to make a new spline in a sprite shape 2D

#

in code

visual dagger
#

im not cross posting because this is a different question, this is how i draw the arcs which im showing in the image belowcs //Draw upper arc and lower arc Handles.DrawWireArc(scientist.visionPosition.position, scientist.visionPosition.up, upLeftEndpoint - scientist.visionPosition.position, scientist.xVisionAngle, scientist.visionRadius); Handles.DrawWireArc(scientist.visionPosition.position, -scientist.visionPosition.up, downRightEndpoint - scientist.visionPosition.position, scientist.xVisionAngle, scientist.visionRadius);

#

how can i tilt these arcs to be pointing in the same direction as the lines which i marked orange in the picture below?

visual dagger
dapper schooner
#

Crazy question but I can't seem to find the list of supported items for UI Toolkit. Trying to make property drawers for custom playable clips but its not working even though everything else works. Anyone know where I can find the supported elements list?

rocky basalt
tardy moss
#

for me it is one one because it sounds like premature optimization

rocky basalt
#

probably. that's tangential to what they said though

tardy moss
#

yeah but to me there were not any specific reason given for doing this except that it "might" help performance

crude mortar
#

because it usually indicates a design flaw. Inheritance, when properly used, is not supposed to require that you know specifically which type of inherited class you are dealing with (assuming you are passing around the base class)

rocky basalt
rocky basalt
crude mortar
#

the reason it was likely a red flag was because this seems to be something you are doing often (every second or so), which means it might be part of your core game code

leaden ice
crude mortar
#

and could turn into a larger problem down the road

rocky basalt
#

Gotcha

#

This is the only place I'm using inheritance in my codebase (well actually I'm not using it at all, still haven't implemented my 'idea').. for whatever reason inheritance feels like a problem waiting to happen

crude mortar
#

it usually is 😆

#

but you can definitely use it correctly and be effective with it

#

it is always somewhat of a difficult topic though, especially in game development where everything is so dynamic

#

keeping it simple is usually best

rocky basalt
#

a lot of beginning unity c# learning materials teach inheritance early on, which in my opinion is not the best use of time. i remember dabbling and quickly realizing it wasn't worth it

crude mortar
#

what is your current inheritance used for?

shrewd mulch
tardy moss
rocky basalt
# crude mortar what is your current inheritance used for?

In simple terms ClassA and ClassB are similar and can both be referenced by ClassC. I wanted to hold a list of ClassA+B in ClassC, instead of one list for each Class. Purely for streamlining <---- now that is likely premature optimization/OCD - haha- but I like to use these moments as learning opportunities

crude mortar
# rocky basalt In simple terms ClassA and ClassB are similar and can both be referenced by Clas...

well what you would do, if using polymorphism correctly, is define the "similar" parts inside of a common base class, then override the similar parts if necessary in each derived class. Then, when iterating over the list, you wouldn't care which one (ClassA or ClassB) you are iterating over, because the functionality you need would be defined in the base class. You could also use an interface instead of a base class if that worked better for what you wanted.

rocky basalt
#

yeah, thing is ClassB's are sort of 'clusters' of ClassA so don't have much overlapping behavior. After my recent refactor I'm realizing I can probably get rid of all behavior in ClassB altogether tho, and have it simply be a data container of lists of ClassA.

#

But then I have to spend a few more hours refactoring. Wahh.

leaden ice
rocky basalt
#

don't they always say there's multiple ways of doing things in programming 😅

spring creek
rocky basalt
#

multiple 'valid' ways?

crude mortar
#

depending on how complex it is, there could be many many valid ways

spring creek
crude mortar
#

it's really more of an art than a science most of the time, at the high level

rocky basalt
#

sure seems like it.

warm kraken
#

hey guys

#

i have an issue here

#

i have a ball with a rigidbody which i control with torque

#

the issue is that on one single collider

#

surface

#

it can be controlled smoothly

#

but whenever 2 colliders overlap (because im doing a lot of modular stuff)

rigid island
warm kraken
#

so in the video i first test the ball controller on a modular surface

#

then in one surface

rigid island
#

video must mp4 cause its not working

warm kraken
#

oh sry

#

heres the mp4 version. i first test it on many overlapping surfaces and then with just a single one

rigid island
#

common issue

warm kraken
#

is there a way to solve this? perhaps an asset or something?

rigid island
#

yeah in 3D its even more fooked

#

"ghost collision"

#

you can try to maybe combine the dynamic meshes into 1 mesh

warm kraken
#

solved it by setting default contact offset to a lower value thank you for the help

dense tusk
#

ahoy lads. trying to formulate a thingy where i can call a method like such:

//psuedo-code
if (click on object)
{
  scriptOnObject.MethodToCall();
}

i have what i'm guessing is called an abstract class, and some scripts that inherit (i think that's the right term) from the class.
https://paste.ofcode.org/378PCYkiFdicXfYBLGSJugP //abstract class

//how the script above gets called
if (hit.collider.TryGetComponent<InteractScript>(out InteractScript t))
{
    interactScript = hit.collider.GetComponent<InteractScript>();
    interactScript.UseMethod();
}

my only grievance with this set up is that i have to make another script for each override i want to create. which is fine, but i wanted to know how i might achieve the same thing without making a new script for each one. maybe i don't even need to right now, i just don't know how to make it work in a single script ¯_(ツ)_/¯

somber nacelle
#

a few things, first what do you mean that you have to make another script for each override?
and also, you don't need that GetComponent call inside the if statement. you have a local variable t that the component reference is being stored in, just use that

dense tusk
#

oh facts. thanks

#

so the only way i thought i could make this work is to make the original script with the abstract class, and then make another script for the override methods and attach the script with override methods to an object.

somber nacelle
#

yes, you cannot instantiate an abstract class. so you need a concrete implementation that is not abstract. that is what you would attach to your gameobjects. your TryGetComponent will still get those other components that inherit from the abstract one since they are instances of the abstract class

dense tusk
#

gotcha. so with my current method, there's not really a way to do it without those concrete implementations in the form of separate scripts inheriting from the abstract one

somber nacelle
#

right, but i'm not seeing why that is a problem. that's literally how abstract classes work

dense tusk
#

you're right, its not. just trying to learn is all

#

i've messed around with unity events and i wasn't sure if maybe it would work similarly to that where it's kinda like a drop down of methods, so i was just checkin. i appreciate the explanation. i understand it more now

#

are there any other methods that can do something similar? this is the one i settled on, and it just happened to be the first one i learned about

somber nacelle
#

well your abstract class could be an interface instead since it's just a couple of abstract methods

dense tusk
#

those seem useful. thanks for the tip

round violet
#

is ignore collision from rigidbody an on/off toggle or a one time ignore ?

lean sail
round violet
#

i figured a better way to sort my stuff

round violet
lean sail
round violet
#

i didnt mean it like a component parameter

leaden ice
leaden ice
round violet
#

im in VS so i cant directly translate notlikethis

round violet
#

VS = visual scripting

leaden ice
#

Visual scripting uses the same APIs afaik

round violet
#

yes but sometimes there is some weird stuff

nimble cairn
#
public class WallTextureGenerator : MonoBehaviour
{
    [SerializeField] Transform walls, floor;

    [SerializeField] Material[] wWallMaterials, bWallMaterials, wFloorMaterials, bFloorMaterials;

    void Awake() {

        Renderer[] wallTiles = walls.GetComponentsInChildren<Renderer>().Where(c => c.tag == "white" || c.tag == "black").ToArray(),
                   floorTiles = floor.GetComponentsInChildren<Renderer>().Where(c => c.tag == "white" || c.tag == "black").ToArray();

        int wWallMatLength = wWallMaterials.Length,
            bWallMatLength = bWallMaterials.Length,
            wFloorMatLength = wFloorMaterials.Length,
            bFloorMatLength = bFloorMaterials.Length,
            
            wallTilesLength = wallTiles.Length - 1,
            floorTilesLength = floorTiles.Length - 1;

        for (int i = 0; i < wallTilesLength; i++) {
            wallTiles[i].material = wallTiles[i].tag == "white"        // Here
                ? wWallMaterials[Random.Range(0, wWallMatLength)]
                : bWallMaterials[Random.Range(0, bWallMatLength)];
        }

        foreach (Renderer r in floorTiles) {
            r.material = r.tag == "white"                              // And here
                ? wFloorMaterials[Random.Range(0, wFloorMatLength)]
                : bFloorMaterials[Random.Range(0, bFloorMatLength)];
        }
    }
}

Can anyone tell me why I'm getting an index outside bounds of array error on line 25?

rocky basalt
#

For my non-MonoBehaviour scripts, is there a need to attach them to GameObjects to make them work? Or can I simply create new MyScript script = new MyScript(), and reference/update that script via a List I add it to?

deep oyster
#

No it has not??? I'm succesfully getting this image in my start function, never deleting it, but now it says it doesn't exist???

leaden ice
nimble cairn
#

@leaden ice wallTiles[i].material = wallTiles[i].tag == "white"

#

The first line of the for, and foreach loop throw an error

leaden ice
#

So the random access in the ternary operator is accessing an invalid index of the empty array

nimble cairn
#

That was the case!! Does unity clear the array if I rename the variable??? I had previously allocated the materials and now in the inspector they have vanished.

#

@leaden ice +rep

#

Also, thoughts on the efficiency of the script? This just feels like it's the best way to handle a large amount of tiles for my levels.

leaden ice
nimble cairn
#

Good to know....

#

Thank you!

#

@leaden ice Just at a quick glance, what are your thoughts on the efficiency of the script?

lean sail
rocky basalt
#

I know you can't add it if it's not MB, I guess my question was more, do I NEED to make them MB's + add them to GO's to make everything run properly.

They don't use any MonoBehaviour functions, they're more like configuration/data containers

nimble cairn
#

@leaden ice And do you believe I should be using the for or foreach loops?

leaden ice
#

The use of tags is kinda janky and especially .tag is a known garbage generator.

But what's the efficiency concern about? Is this causing a performance issue?

nimble cairn
#

I use .tag because the game is a "portal-like`` and I tag walls white or black to determine if the player can interact with them.

leaden ice
#

Tags are inefficient for this compared to an enum field or something on a component.

#

And especially the use of .tag is a known GC allocator

lean sail
rocky basalt
leaden ice
cold egret
#
  • Given a struct type that i deserialize fom json, will the instance of it be boxed by the time i get my hands on it? If so, then is there any way to escape allocations during the deserialization process?
rose estuary
#

Hello, anyone has experience with Unity Cloud code modules?
Trying to trigger a module function, which should sent notification to a player (from the push messages example), but receiving error:
Error starting gRPC call. MissingMethodException: Method not found: 'Void Google.Protobuf.MessageExtensions.WriteTo(Google.Protobuf.IMessage, System.Buffers.IBufferWriter1<Byte>)'.`

harsh root
#

In Unity Vr I have an issue with rotation. I got an object with a configurable joint. When this object rotates. The child objects rotate in the oppisite direction

#

anyway to solve this?

rancid jolt
#

The character is moving fine, But when I am trying to rotate the body in the direction of movement. It is working but in a weird way.

Here is the full code

stoic ledge
#

Is there a way to exclude certain folders from build for certain platforms?
E.g. I have a Firebase Admin SDK and I want to include it only into the headless unity build.

upper pilot
#

Is there a reason why I should or should not use Events for all/most of my code in order to decouple my scripts?
i.e. if I want to hire a new party member, I dont want to directly call Party.AddMember(hero);
But instead I can do onMemberHired?.Invoke(hero);
Is that a better way? What is a downside?

#

Even tho all my scripts go through static Game instance:
Game.Instance.partyManager.AddMember(hero);

#

But they still directly call a function.

#

Should I at least do:

Game.Instance.AddMember(hero);

// Game script:
void AddMember(Hero hero)
{
    partyManager.AddMember(hero);
}
#

Tho even with events, if I subscribe to them I am still coupled somehow?
I guess in that case I can subscribe to those events with my Game class and call proper methods from it?

latent latch
#

Well, it depends how you want to set it up. If you call a method to insert this hero into the party, then you'd have to implement additional logic inside of this method to update those that are dependent on knowing this hero was added. Using events, you call the invoke and everyone listening onto this method will be notified, so they can use that info with their own internal logic to update any data.

upper pilot
#

Yeah but isnt decoupling about not having any connection to outside?

#

I.e. hiring manager and party manager dont know about each other existence

#

So I can cut them out into new project without needing the other script with me.

latent latch
#

events are good for decoupling or limiting what's passed around

#

but you could also use interfaces otherwise

upper pilot
#

So my current thought is to use a middleman to listen to all events and call proper functions)

#

How would I use interafaces in this case?

latent latch
#

The partymanager wouldn't have direct references to the party members, but an interface of implementation of each party member

#

IStats, ect

upper pilot
#

oh, but isnt that still coupling?

#

well kinda

latent latch
#

kinda I guess, but if you only have a part of the data it's not like you can use anything outside of IStats

upper pilot
#

Makes sense, I will have to play around with it.
I just want to avoid different modules talking to each other at all if possible

#

its getting out of hand already and we are not far in development 😄

#

Even tho I am using Events and trying to minimize coupling, but its not easy.

#

In some cases we just call a function directly from another module.

#

We do separate UI from code tho(using Events) which is good.

latent latch
#

usually events are my goto, but when you're dealing with monos you can't set them in the constructor, so it's not always like a true decoupling

#

usually you want to reuse monos anyway so not that big of a deal

upper pilot
#

Alright, thanks. I will probably need an UI manager of sorts that has an "Init" function that I can call when my Game is loaded right?
Otherwise I have trouble with order of execution and I cant subscribe to events which dont exist yet.

#

Maybe I do it wrong tho hmm

#

I might need to new() events in Awake, and subscribe in Start

tired aspen
#

I have list that is from type BlockPositionClass

public class BlockPositionClass
{
    public Vector3 vector;
    public int myInt;

    // Beispielkonstruktor
    public BlockPositionClass(Vector3 vector, int myInt)
    {
        this.vector = vector;
        this.myInt = myInt;
    }
}

Now i want to delet an element. (newBlockPosition)

            // Erstelle ein neues BlockPositionClass-Objekt
            BlockPositionClass newBlockPosition = new BlockPositionClass(currentGridPosition, blockType);

            Debug.Log(newBlockPosition.vector);
            Debug.Log(newBlockPosition.myInt);
            blockPositions.Remove(newBlockPosition);

But when i try this nothing happened.
And I already teste if the numbers are wrong(currentGridPosition, blockType) but they are correct.

latent latch
#

Managers, or anything that aren't dependent in awake(), everything else in start. There's also the custom execution ordering in the settings.

upper pilot
#

and I need to Initialize game data after Start is done executing uh this is hard <_<

#

I tried the custom execution and it didnt seem to work for me, but I will have to find a way to load things in some order i.e.

  • setup events first
  • subscribe
  • load data
  • invoke those events
cosmic rain
cosmic rain
tired aspen
#

this is the code where i add the block to the list.
First I place the object in my project, it gets added to the list but when try to delete the block it just stays in the list.

 private void placeObject(BuildingObjectBase obj)
    {
        if (escapeMenu.InEscapeMenu) return; // wenn im escape menu dann soll alles aus sein

        if (!GroundMap.GetTile(currentGridPosition))
        {
            if (CantBuildOutsideTheBorder(currentGridPosition)) return;
            
            GroundMap.SetTile(currentGridPosition, obj.TileBase);
            HandleDeselection();
            getsObjectsGridPostion(currentGridPosition);

            //Checks if what the tile that was placed was
            int blockType = -1;

            if (GroundMap.GetTile(currentGridPosition) == tile1)
            {
                blockType = 0;
            }
            else if (GroundMap.GetTile(currentGridPosition) == tile2)
            {
                blockType = 1;
            }
            else if (GroundMap.GetTile(currentGridPosition) == tile3)
            {
                blockType = 2;
            }

            blockPositions.Add(new BlockPositionClass(currentGridPosition, blockType));
        }
    }
#
 private void deleteObject()
    {
        if (escapeMenu.InEscapeMenu) return; // wenn im escape menu dann soll alles aus sein

        if (GroundMap.HasTile(currentGridPosition))
        {
            //Checks if what the tile that was placed was
            int blockType = -1;

            if (GroundMap.GetTile(currentGridPosition) == tile1)
            {
                blockType = 0;
            }
            else if (GroundMap.GetTile(currentGridPosition) == tile2)
            {
                blockType = 1;
            }
            else if (GroundMap.GetTile(currentGridPosition) == tile3)
            {
                blockType = 2;
            }

            // Erstelle ein neues BlockPositionClass-Objekt
            BlockPositionClass newBlockPosition = new BlockPositionClass(currentGridPosition, blockType);

            Debug.Log(newBlockPosition.vector);
            Debug.Log(newBlockPosition.myInt);
            blockPositions.Remove(newBlockPosition);

            // Entferne es aus der Liste, wenn es bereits existiert (optional)
            /*int index = blockPositions.IndexOf(newBlockPosition);
            blockPositions.RemoveAt(index);
            Debug.Log("Dleete");*/

            GroundMap.SetTile(currentGridPosition, null);
        }
    }
upper pilot
#

You are trying to remove a block position you just added on the same line of code

#
            // Erstelle ein neues BlockPositionClass-Objekt
            BlockPositionClass newBlockPosition = new BlockPositionClass(currentGridPosition, blockType);

You made a new instance here then you delete it.

cosmic rain
upper pilot
#

Make a function that returns BlockPositionClass instance based on your coordinates.(a foreach loop might do, compare grid position and block type then return it)

#

Tho I am sure there are better ways to do it, but this will work too.

#
            BlockPositionClass blockInstance = GetBlockInstanceAt(currentGridPosition, blockType);
            blockPositions.Remove(blockInstance);
tired aspen
#

But than i have another question

int index = blockPositions.IndexOf(newBlockPosition);
            blockPositions.RemoveAt(index);

and then why doesn't it work?
that gets the specific index

upper pilot
#

Because newBlockPosition was just created, its different from the one you placed earlier.

#
            BlockPositionClass newBlockPosition = new BlockPositionClass(currentGridPosition, blockType);

This code makes a completely NEW instance of a block class, it has nothing to do with the one you created inside "placeObject" function

#

You need to search your List in a foreach loop(or regular for loop) and find the block you want.

tired aspen
#
            BlockPositionClass newBlockPosition = new BlockPositionClass(currentGridPosition, blockType);

            BlockPositionClass itemToRemove = null;

            foreach (BlockPositionClass item in blockPositions)
            {
                if (item.Equals(newBlockPosition))
                {
                    itemToRemove = item;
                    break;  
                }
            }

            if (itemToRemove != null)
            {
                blockPositions.Remove(itemToRemove);
            }

i used this thanks for the help. ^-^

upper pilot
#

This shouldnt work -.- Why are you still doing new

#

Equals might simply compare the type, not sure, but the code above shouldnt work as its the same thing as before right?

#
            BlockPositionClass newBlockPosition = new BlockPositionClass(currentGridPosition, blockType);

Delete this and dont use it when deleting stuff from the List.

#

foreach (BlockPositionClass item in blockPositions)
{
    if(item.positon.x == currentGridPosition.x && item.y == currentGridPosition.y && item.blockType == blockType)
    {
      blockPositions.Remove(item);
      break;
    }
}
#

You need this if statement to find an item

#

There is no other code needed.

tired aspen
#

ok

upper pilot
#

Ideally you put it into a function and do return item; so you can remove it elsewhere since that function could be useful for other things later.

tired aspen
#

thanks for the idea

placid compass
#

Hello, I have a question.
I have a character that uses Character controller for movement. I also have a object pick up mechamic. So when I pick up the object and walk around with it it just goes thru the walls even tho it has a collider. I tried adding another collider to the player that turns on when the object is picked up but it still goes thru the wall. The character stopps when the character controller collider hits the wall but not when any other collider does. Any idea how I can solve this? Thanks

wicked berry
#

why does this doesnt return me a string?

deft timber
#

if you need to modify the anchoredPosition then just modify it, what's the problem?

#

.anchoredPosition

#

Vector2 screenPoint = RectTransformUtility.WorldToScreenPoint(Camera.main, worldPosition);

#

Vector2 anchoredPosition = transform.InverseTransformPoint(screenPoint);

thick socket
#
    public DamagePopup pfDamagePopup;

   public void ShowText(Vector3 position, int damageAmt)
    {
        DamagePopup damagePopup = BasicPooling.instance.BasicPool[pfDamagePopup].Get().GetComponent<DamagePopup>();
        damagePopup.Create(position, damageAmt);
    }```
#
public Dictionary<Component, ObjectPool<Component>> BasicPool = new();
    [SerializeField] List<Component> items;
    public static BasicPooling instance;
#

code doesn't work because "key doesn't exist"

#

if I open prefab and drag in the script it creates fine

#

however when I try to release it inside of the DamagePopup Script it throws and error for "can't find key" also

#
BasicPooling.instance.BasicPool[this].Release(this);
#
System.Collections.Generic.Dictionary`2[TKey,TValue].get_Item (TKey key)
leaden ice
thick socket
#

shouldn't the component be the same though?

leaden ice
#

so you'll need a reference to the prefab

leaden ice
#

the prefab is the original

thick socket
#

oh I gotcha, that solved it thanks!

thick socket
#

Anytime I try and drag in a prefab do I need to open the prefab in another inspector and grab the component that I need to be the key?

leaden ice
#

that will open a separate special inspector for it

#

then open this pool thing and you can drag the title bar of the specific component in.

thick socket
#

awesome thanks!

steep herald
#

Has unity developed a haptics library for mobile yet?

deft timber
#

haptics library for mobile? wdym

simple sable
#

Hey everyone, I have a quick question.

By using "[RequireComponent(typeof(Light2D))]" I make sure that the gameobject my script is attached to will also have a Light2D. But, is there a way make it so that I can't (by mistake) disable the Light2D?

leaden ice
#

Are you worried about disabling it in the inspector or in code?

#

If you're worried about the inspector you could use OnValidate to check if the light has been disabled and enable it or print a warning message

simple sable
icy schooner
leaden ice
icy schooner
#

Yeah that

simple sable
#

Ohhh.. I see.

#

Thanks for the help!

spring creek
# simple sable Ohhh.. I see.

The inverse of what they're saying is also important. Disabling a script will not stop all code from running
Only unity messages

round violet
#

Except in c# script is there a way to do childs of prefab or stuff ?

#

Like create a child of a Actor BP in UE (if anyone knows)

spring creek
round violet
spring creek
round violet
#

Sad

#

Ty for the response

hexed pecan
#

A prefab variant can 'inherit' everything from another prefab and then you can modify the variant as you like

round violet
#

Oh nice

#

Is it built in?

#

@hexed pecan (forgot to respond)

spring creek
#

Won't make child classes, it will make variants of the gameobject to use.
They are very useful

heady iris
#

Can I check how much time is being spent waiting for the target FPS?

I am writing some code to automatically set the render scale. Currently, it just lowers the scale if the FPS is too low and raises it if the FPS is too high. This is causing some annoying "wobbling" as it goes up and down, so I'd like to change it.

My new strategy is going to be to only use a few increments -- 100%, 80%, 60%, etcetera. I want to change increments only after the FPS has gone out of range for too long. This is easy if the framerate is too low.

But if Application.targetFrameRate equals the framerate my scaler is trying to maintain (let's say 60), the scaler will never see the FPS going much above 60.

#

I figure I could just check how much extra time each frame has, and raise the scale if there's lots of spare time

#

Alternatively, a better strategy for picking the render scale would also help me out here :p

heady iris
round violet
heady iris
#

All of my various settings-menu entries are variants of a single "setting entry" prefab

polar marten
round violet
heady iris
#

this is specifically in the HDRP, if that matters

#

Unity triggers this scaling if performance data suggests that the frame rate is about to decrease as a result of the application being GPU-bound.

this sounds promising

#

Ah, I see that FrameTimingManager can tell you how much frametime is gpu-based

polar marten
#

is that your objective?

heady iris
#

yes, I want to have an option to make the render scale auto-adjust

#

I am currently controlling the dynamic resolution scale myself

polar marten
heady iris
#

I do not know where these boxes are.

polar marten
heady iris
#

I am aware of how to use HDRP's dynamic resolution scaling. I was not aware of how to make Unity automatically adjust the scale to maintain a target framerate.

#

I just noticed the HDDynamicResolution component, which is what I need

waxen jasper
#

I need to channel more brain power on this one. I posted in machine learning channel but you don't need to understand ml agents to understand what I'm trying to solve. Essentially I'd like to get an average location of all the body parts and determine if the velocity of that is moving in the direction of the target.

Hey so training my 2d rigidbody stick figure guy. any body have any suggestions on how I can reward it for moving towards the target? the dot approach works best but Is there a way i can get an average of all the body parts, if you get what I'm trying to say. Right now the stick figure immediately leans towards the target at a 45 degree angle.


            // Calculate the dot product between the agent's velocity and the direction to the target
            float dot = Vector2.Dot(
                spine.gameObject.GetComponent<Rigidbody2D>().velocity.normalized,
                toTarget.normalized
            );

            // Reward the agent if the dot product is positive (i.e., moving towards the target)
            if (dot > 0)
            {
                HandleReward("dot", 10f);
                AddLabel("dot", dot);
            }
            // Punish the agent if the dot product is negative (i.e., moving away from the target)
            else
            {
                HandleReward("dot", -12f); 
            }
leaden ice
#

same as basically any quantity

polar marten
#

you should use this script

heady iris
polar marten
#

i am not sure why this isn't delivered in the hdrp package

#

but this will correctly achieve what you want

heady iris
#

It is, in a similar form, as HDDynamicResolution

#

I missed it when reading the docs the first time.

polar marten
#

ah i see, they do put it in the package

#

sorry about that

#

that must be what i was remembering

heady iris
prisma yacht
#

I'm trying to rotate a 3rd person character using the mouse like this:

        float mouseXInput = Input.GetAxisRaw("Mouse X");
        rotationY += mouseXInput * mouseSensitivity;
        Quaternion localRotation = Quaternion.Euler(0f, rotationY, 0.0f);
        transform.rotation = localRotation;

but the rotation only happens when the cursor is moving

#

I want it to rotate continuously

polar marten
heady iris
#

Mouse X is how much the mouse has moved

prisma yacht
#

input.mousePosition then?

heady iris
#

Describe how you want the camera movement to work.

waxen jasper
heady iris
polar marten
#

i am not sure what is going on here, but i think you want to reward decreasing distance to target over short periods of time, not the velocities of individual body parts

heady iris
#

and yes, you should reward that

polar marten
#

@waxen jasper the approach you are taking with velocity is wrong.

heady iris
#

Instantaneous velocity or momentum might be going the wrong way from time to time

#

but this shouldn't be punished

#

imagine trying to climb stairs without your center of mass ever going down

frosty token
#

I'm for help with quarternion rotations, i've tried for over a year to get this right, but i keep finding edge cases that ruin a very fundimental part of my game. I've made a small separate project that should illustrate the issue. While the rigidbody is under torque the plane will not only turn on the local z axis, but also turn through the y-axis. I don't understand why. I hope the image helps with what i'm trying to achieve. The left is a "normal turn" by the player. However, it should also be possible (at any point) to flip the plane over. Note that the game is 2.5D and all movement on the x-axis is locked. Basically i want to be able to angle the plane on the x-axis only, and rotate the plane on the z-axis only. You will receive a free copy of my game if I manage to solve this haha.


    void FixedUpdate()
    {
        currentSpeed = Mathf.Clamp(currentSpeed, 0f, maxSpeed);

        // pitch the plane based on input
        rigidbody.AddTorque(transform.right * flipTarget * rotationSpeed * Time.deltaTime * Input.GetAxis("Horizontal"));
        rigidbody.velocity = transform.forward * currentSpeed;

 //---->// TODO: gradually level out the wings to be perpendicular to imaginary z-y plane
        
        // TODO: keep the nose of the plane pointing along the imaginary z-y plane

        // reset the x position
        Vector3 pos = transform.position;
        pos.x = 0f;
        transform.position = pos;
    }

    void OnDrawGizmos()
    {
        // flipTarget means inverted or not depending on if the plane is facing z+ or -z
        Vector3 cross2 = Vector3.Cross(transform.up, transform.forward * flipTarget);
        
        Handles.Label(transform.position, @$"
            Cross2: {cross2:F1}

        ");
    }
prisma yacht
#

regardless of where the cursor is

leaden ice
heady iris
#

The camera should only move when you move the mouse.

gleaming blaze
#

hi everybody

#
public abstract class Fadeable : MonoBehaviour
{  
    public virtual async void ChangeCurrentByDayTime(DayTime dayTime, CancellationToken token) 
// if Application.exitCancellationToken.IsCancellationRequested => method must stop. how can i do this?
    {
        await FadeIn(token);
        
        ChangeTextureByDayTime(dayTime);
        
        await FadeOut(token);
    }
    public virtual async Task FadeIn(CancellationToken token)
    {

    }
    public virtual async Task FadeOut(CancellationToken token)
    {

    }
    public abstract void ChangeTextureByDayTime(DayTime dayTime);
} 
prisma yacht
heady iris
gleaming blaze
heady iris
#

sounds like you want to lock the cursor

frosty token
polar marten
#

I'm for help with quarternion rotations

waxen jasper
prisma yacht
#

and I don't think it lets you lock cursor once it's built into a webGL window

polar marten
gleaming blaze
#

how to make the asynchronous method react to the fact that the token sends a cancellationRequest and stops?

heady iris
#

you just have to do it in response to interaction.

prisma yacht
#

oh ok

polar marten
prisma yacht
#

until you bring it back to the center

heady iris
#

I’ve been having a hard time understanding what you’re asking for!

prisma yacht
heady iris
#

Use that to decide how to rotate

prisma yacht
heady iris
#

Suppose the mouse is at [300,200] and the center of the screen is at [400,200]

#

The difference is [-100, 0]

#

So your mouse is to the left of the center. You should rotate left.

waxen jasper
swift falcon
#

can anyone help me? this code right here is responsible for freezing my unity editor 2 times

simple egret
#

Infinite while loop

swift falcon
#

yea but how

simple egret
#

Your objects are destroyed at the end of the frame when you call Destroy(), except the end of frame is never reached because that loop is executing

#

You should be using a for loop to go through all children of the object

swift falcon
#

oh yea thats genius

#

ty

hexed pecan
swift falcon
swift falcon
#

its a little more optimized memory

simple egret
#

"an error" - mind reading is not installed on this computer. Please state the error

swift falcon
simple egret
#

Yes you indeed cannot destroy a Transform

swift falcon
#

lemme see

simple egret
#

The for loop loops too much

hexed pecan
#

Yeah, the <= should be <

swift falcon
#

i wonder why

swift falcon
hexed pecan
#

First object is 0

#

5th object is 4

#

Etc.
So the last item in an array is always count - 1

swift falcon
#

yay it works perfectly

swift falcon
hexed pecan
#

There's no variable i now, you work with child directly

#

Just Destroy(child.gameObject)

swift falcon
#

knew it, thanks

hexed pecan
#

Both ways work - I just find foreach cleaner here

swift falcon
swift falcon
#

and yes its cleaner

hexed pecan
pine carbon
#
void Update(){
    
    if (Input.GetKeyDown(KeyCode.Space)) {
        Vector3 torque = rb.GetAccumulatedTorque();
        rb.AddForce(new Vector3(
             torque.z, 0, torque.x
        ).normalized * jumpForce, ForceMode.VelocityChange);
        rb.AddForce(new Vector3(0, jumpForce, 0), ForceMode.VelocityChange);
        Debug.Log(torque);
    }
}
#

i used this code to make the ball jump in the direction its rolling but it works different sometimes

hexed pecan
#

Not sure why you are using accumulated torque for the force

pine carbon
#

to make the ball jump in the directions its rolling

hexed pecan
#

Try using rb.velocity to get the direction instead?

pine carbon
#

its same

#

oh wait a second

hexed pecan
pine carbon
#

it works wery well now thankyou

gleaming blaze
#

you've really helped me

swift falcon
#

why does it give me this error

leaden ice
#

assuming the highlighted line is line 45

#

btw C# convention is for class names is to use PascalCase, not camelCase

swift falcon
leaden ice
swift falcon
#

i set its value in awake()

leaden ice
#

it won't run if you don't actually have an active instance of this script in the scene

swift falcon
#

wdym

leaden ice
# swift falcon wdym

If you don't have any object with the newAnswer script attached to them in the scene, the code won't run

#

naturally

swift falcon
leaden ice
#

Another possibility, if you DO have such an object in the scene, is that the other code is running BEFORE this Awake code does.

swift falcon
#

how do i fix

leaden ice
swift falcon
leaden ice
leaden ice
# swift falcon

Also which object have you selected here that we're looking at? is this an object in the scene?

swift falcon
leaden ice
spring creek
#

It's best to not crop things so much btw. It would be helpful to see more of the editor than just those small snippets

leaden ice
#

not the one you originally showed. You misled me about which line it was

#

look at liune 45

#

it's either Answer.instance that's null or questionObj

#

questionObj seems quite likely since you're using GameObject.Find for some reason

#

That's incredibly flimsy

swift falcon
leaden ice
#

Asynchronously?

swift falcon
#

like at the end of the frame

leaden ice
#

No, it's just really flimsy because the object name has to match perfectly

#

and has to be active

#

Why not just use direct references etc

swift falcon
spring creek
#

Is the name of questionObj just a plain number? Because that is what you seem to be searching

swift falcon
#

like without atributting it in inspector

spring creek
spring creek
leaden ice
swift falcon
spring creek
swift falcon
leaden ice
spring creek
swift falcon
#

the game object changes from the object named 1 to the object named 2

leaden ice
spring creek
swift falcon
leaden ice
#

Arrays are the most basic collection type in C#

#

it's a collection of multiple objects in one variable

spring creek
swift falcon
spring creek
leaden ice
terse turtle
#

I'm currently trying to create a working door with my Tilemap Door. However, I don't think there is a way to do that. So I did the next best thing and will be using a sprite door that replaces the Tilemap Door on the Grid. I want to know if this is the only way and how should I go about doing so?

#

The Game is TopDown 2D and the player can see the door like in the Picture. I want to make the door open and then able to walk into. Then Teleport to a new scene.

dusk creek
#

´´´cs

How do i make it so when i press e and im not grounded the camera quikcly zooms in and out???

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

public class Dash : MonoBehaviour
{
public float dashDistance = 5f;
public Camera cam;

private CharacterController controller;
private PlayerMotor playerMotor;

public float dashTime = 0.5f; // Duration of the dash
public float zoomFOV = 60f; // Adjusted FOV during dash
private float originalFOV;
private float dashTimer;

void Start()
{
    controller = GetComponent<CharacterController>();
    playerMotor = GetComponent<PlayerMotor>();
    originalFOV = cam.fieldOfView;
}

void Update()
{
    zoomFOV = cam.fieldOfView - 10f;
    if (Input.GetKeyDown(KeyCode.E) && !playerMotor.isGrounded)
    {
        Foward();
        cam.fieldOfView = Mathf.Lerp(zoomFOV, cam.fieldOfView, 10); // Smoothly restore FOV
    }



}

private void Foward()
{
    Vector3 dashDirection = cam.transform.forward;
    Vector3 dashVector = dashDirection * dashDistance
    controller.Move(dashVector);
}

}`

tribal ginkgo
#

Whoops didnt mean to delete me other message but anyway why would that be more optmised?

#

Tiles are annoying to move around and managing multiple grids is annoying too

terse turtle
#

I saw a notification but I don't see where it came from. Did someone send me something?

#

Are you helping me?

#

Next time @ me please

#

I'm a bit confused on what you are trying to tell me here.

#

Is there a way to use sprites with Tilemaps?

#

Because the way I was going to do it is this: Create a Door Sprite with Animator/Animations. I simply just cover the empty tile that the door was supposed to go in the Tilemap, but since I am using a Sprite I would just move the Sprite Door there instead.

#

Yes, that's why I was in need of help.

#

If this is possible then I would like to know how.

wind needle
#

Hi! I have a question about the context of coroutines:

I have a coroutine that creates a game object, and sets the parent to the current components game object.

I have created a method in that same component that simply starts the coroutine:

void CreateStuff() {
  StartCoroutine(CreateStuffCoro());
}

IEnumerator CreateStuffCoro() {
  var o = new GameObject( ... );
  o.transform.SetParent(transform, false);
}

However, when I call this method from another component (attached to another game object), the new game object is added as a child of the caller gameobject, instead to the gameobject of the component that has the above methods! What is the logic here?

terse turtle
#

This is a lot of Information to take in. I should note that I've never used Tiles in code, so all of this is very confusing.

#

Thank you.

#

By setting, do you mean when I paint the Tiles?

#

What is ref? A reference?

kind panther
#

does anyone know shader graph??

terse turtle
#

That complicates things even more for me. Is there a very simple explaination that a begginer can understand?

kind panther
#

im trying to pixelate an img but i want to have a limit of colors(like 10) to the final image,any ideas how?

terse turtle
#

I'm confused on "ref". Does it matter alot here?

kind panther
terse turtle
#

No.

#

Will I be able to the Door Functionality without using my own custom Classes/Ref?

#

Also, that makes better sense to me*

#

So the value is changed to 4, but the "int" doesn't get effected?

#

Or the int's Value is moved but not the actual int. Which means int still stays where it was but the value gets taken.

hardy tendon
#

hi, does anyone here know anything about XR or VR in general?

polar marten
#

that is the simplest and best approach

leaden ice
polar marten
#

Any reference to a better approach would

terse turtle
#

Okay. But is this to help with door? Because it just seems like I'm learning how variables work?

hardy tendon
terse turtle
#

This is becoming a long conversation. Is there a way to make a thead so that I can go back to the conversation if I forget something?

#

I tried it. Its too messy

bitter quarry
#

is this the right place to ask a question about code that i need help with?

#
using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using VRC.Udon;

public class Ball : UdonSharpBehaviour {
  public float maxSpeed = 1.0f;
  Vector3 velocity = Vector3.zero;

  void Update() {
    Vector3 randomVel = new Vector3(Random.Range(-0.5f, 0.5f), Random.Range(-0.5f, 0.5f), Random.Range(-0.5f, 0.5f));
    float lerpValue = Vector3.Dot(randomVel.normalized, velocity.normalized);
    Vector3 newV = Vector3.Lerp(Vector3.zero, velocity, Mathf.Lerp(0.5f, 1.0f, lerpValue));
    if (newV.magnitude > maxSpeed)
      newV = newV.normalized * maxSpeed;
    Vector3 newPos = transform.position;
    newPos += newV * (Time.deltaTime * 100.0f);
    if (newPos.x >= 50 - (transform.localScale.x / 2) ||
        newPos.x <= -50 + (transform.localScale.x / 2)) {
      newV.x = 0;
      newPos.x = Mathf.Clamp(newPos.x, -50 + (transform.localScale.x / 2), 50 - (transform.localScale.x / 2));
    }
    if (newPos.y >= 25 - (transform.localScale.y / 2) ||
        newPos.y <= 0 + (transform.localScale.y / 2)) {
      newV.y = 0;
      newPos.y = Mathf.Clamp(newPos.y, 0 + (transform.localScale.y / 2), 25 - (transform.localScale.y / 2));
    }
    if (newPos.z >= 50 - (transform.localScale.z / 2) ||
        newPos.z <= -50 + (transform.localScale.z / 2)) {
      newV.z = 0;
      newPos.z = Mathf.Clamp(newPos.z, -50 + (transform.localScale.z / 2), 50 - (transform.localScale.z / 2));
    }
    transform.position = newPos;
    velocity += newV;
  }
}```
im trying to have a ball go around my world randomly and when i run this it doesnt do anything and i dont know why. can someone help me with this ;-;
zinc parrot
#

Hey how does unity do its motion vectors? I notice that objects spinning very fast can add to the motion vectors even if they are completely occluded
for example this sphere is spinning very fast, but its also completely behind another object
it dissapears if I get closer
unity builtin 2021

#

oh wait its only happening if the near field isnt minimum
well happens less if I am closer or the near field is further

idle mason
#

trying to load a prefab directly, though when I try calling upon smth when its hierarchy it doesnt seem to find it, any ideas?

#

(the method im actually using for getting the child)

leaden ice
idle mason
#

I see, how should I be using it?

leaden ice
sleek spoke
#

I have a simple object pooling system.

To make sure that pooled objects aren't getting destroyed instead of recycled I have added an assert to OnDestroy that will fire if a pooled object is destroyed before having OnApplicationQuit invoked. Here's a screen-shot of the relevant code.

However, this assert fires sometimes when exiting play-mode in the editor.

Anyone know why this might be happening?

leaden ice
#

Beyond that, reaching into the hierarchy of the prefab like that is poor practice.

leaden ice
#

using OnDestroy for this isn't the best idea

sleek spoke
leaden ice
#

not really tbh. I just wouldn't worry too much about it

#

You'll know you have an issue if you get MissingReferenceException in your pool.

idle mason
leaden ice
sleek spoke
spring creek
idle mason
#

I see

#

well ive now set it to work from the file path from the folder its stored in, but again, it doesnt appear to be working h

#

I stored them in the same folder, I can move it back if need be but this is what im working with

spring creek
#

Is the folder called Resources?

#

Wait, you put it in the root project folder? There is no path there

leaden ice
#

Show where the prefab lives

idle mason
#

...im assuming i have to put them in different folders

leaden ice
#

no

#

you still seem not to have read the docs

#

they spell out clearly where to put the asset

spring creek
#

I also spelled it out twice now.
Resources folder.
Literally a folder just named "Resources".... it is a requirement. It will not work otherwise
That folder can be just about anywhere, but it needs to be named that, and you have to include the whole path in the load function

idle mason
#

there, i fixed it

spring creek
#

The fourth paragraph down in the docs is VERY clear

frosty token
#

I think i can rephrase my question a bit now that I understand the issue better. How would I avoid having any rotation on the Y-axis? or if it is unavoidable, how would I make sure that the "nose" of the plane is "glued" to y-axis=0? Thanks for your help!

        currentSpeed = Mathf.Clamp(currentSpeed, 0f, maxSpeed);
        rigidbody.velocity = transform.forward * currentSpeed;

### the _combination_ of these forces will rotate the y-axis, i want to roll in z and pitch in x at the  same time without leaving the y-axis
        rigidbody.AddForceAtPosition(Vector3.down * rotationSpeed / 4f * Input.GetAxis("Horizontal"), transform.position - Vector3.forward);
        rigidbody.AddTorque(transform.forward * flipTarget * rotationSpeed / 10f);
### 
        // reset the x position
        Vector3 pos = transform.position;
        pos.x = 0f;
        transform.position = pos;
leaden ice
long glacier
#

hello there, is there an equivalent to
[ExecuteInEditMode]
but start and not update in edit mode?

leaden ice
#

kinda weird to have only Start in edit mode imo though

#

maybe you want OnValidate or OnReset?

long glacier
#

you mean start?

void Start() {
  #if UNITY_EDITOR
    if (!UnityEditor.EditorApplication.isPlaying) return;
  #endif
}
leaden ice
cobalt jackal
#

So... öhm... I got a problem... I would rly like to know what is bloating this file that much (about 1-2h of working) but after 30m I cant get it to open... trying to split it fails as well... I... I am a bit lost 😄

#

Its the Unity editor log

frosty token
leaden ice
#

You will need something special because it's not a good idea to load an entire 12GB file into memory

#

these applications can load only a portion of the file.

#

If you don't care about the contents, just delete the file!

#

or just delete it anyway and reproduce whatever the issue is

frosty token
#

or you can use git bash which will have tail as well most likely. Or WSL2 if you have it installed, it'll be mounted under /mnt/c/Users/...etc

leaden ice
#

sure that's an option if you have a unix subsystem or equivalent e.g. git bash^

frosty token
#

still, that notepad++ will stream the file, so scrolling around

cobalt jackal
#

damnit

frosty token
#

nooooooooo

cobalt jackal
#

cause... I have 0 idea...

#

I got no manual function writing excessive logs in my unity application

leaden ice
frosty token
cobalt jackal
#

~95% of the doc seems to be this?

#

dafuq

frosty token
#

whoops wrong reply sorry

cobalt jackal
#

I am looking into that now... I need that plugin though... but... I think its broken like this...

#

thanks for helping me getting it open though!

#

rest I can probably fix

#

So... fixed it (for now) thanks for the help!!! - well... this is what happens if you try to develop from home without having a full setup 😄

tidal shadow
#

i have this jump method, only being called in 1 single place which is inside of fixed update
the first if statement executes just fine
but the second one that detects if i let go of space, does not seem to run
anyone have any idea to why?

#

out of 5 times i let go of space, only 1 of those triggered and outputted to the console

leaden ice
#

Input handling goes in Update

#

FixedUpdate doesn't run every frame, so it will miss things like GetKeyUp most of the time

#

btw 20 * Time.deltaTime in FixedUpdate is just always going to be 0.4

tidal shadow
#

oh yeah true
fixedupdate is for physics only

tidal shadow
leaden ice
tidal shadow
#

wow, so thats a little shortcut

shadow nacelle
#

Okay so, I been making a game with a group of people (for a class assignment) and I need a bit of help on some of my scripts and is just wondering if anyone can help me out. So, right now I'm trying to figure out how to spawn 3 different food items on 3 different counters using a counter code I have. (I have many more problems but I'm trying to go step by step)

#

And here’s the code my teacher made

#

But I have almost zero clue how to actually utilize it to get the 3 desired items for each counter

#

And the whole goal is to get those 3 items to spawn so when I pick one up it goes on a 3 second cool down and spawns the desired food back

lean sail
# shadow nacelle

First !code on how to format it properly,
2nd what 3 items are you referring to? You have a single string named item, which will be kinda useless by itself
3rd your teacher made this? It's pretty bad..

tawny elkBOT
shadow nacelle
lean sail
lean sail
shadow nacelle
lean sail
shadow nacelle
lean sail
#

these are just strings still, if you reference a prefab, it would be of type GameObject or some monobehaviour

shadow nacelle
# lean sail read the bot command above on how to post code, photos of your screen really are...

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

public class InvManager : MonoBehaviour
{

public string Inventory;
public string[] possibleItems;
public int score;

// Start is called before the first frame update
void Start()
{
    Inventory = null;
}

// Update is called once per frame
void Update()
{
    
}

public void IncreaseScore(int add)
{
    score = score + add;
}

}

#

like that?

lean sail
shadow nacelle
# lean sail re-read the command
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InvManager : MonoBehaviour
{

    public string Inventory;
    public string[] possibleItems;
    public int score;

    // Start is called before the first frame update
    void Start()
    {
        Inventory = null;
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void IncreaseScore(int add)
    {
        score = score + add;
    }
}
#

there we go t-t

lean sail
#

if you remove the initial space before the cs itll color code it too, but yea still same comment as above. this doesnt refer to any prefabs because its all just strings at the moment

shadow nacelle
# lean sail these are just strings still, if you reference a prefab, it would be of type Gam...

okay so in the table script the invManager is a gameobject so maybe that?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static UnityEditor.Progress;

public class Table : MonoBehaviour
{

    private string item;
    public GameObject invManager;
    public float cooldown = 3f;
    public bool onCooldown = false;
    public GameObject alert;
    public bool randomizeItem = true;
    public int addScore;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player") && (invManager.GetComponent<InvManager>().Inventory == item))
        {
            onCooldown = true;
            alert.gameObject.SetActive(false);
            print("Item Delivered" + (invManager.GetComponent<InvManager>().Inventory));
            invManager.GetComponent<InvManager>().Inventory = null;
            invManager.GetComponent<InvManager>().IncreaseScore(addScore);
            CooldownRequest();
        }
    }

    IEnumerator CooldownRequest()
    {
        yield return new WaitForSeconds(cooldown);
        alert.gameObject.SetActive(false);
        if (randomizeItem)
        {
            int randomIndex = Random.Range(0, invManager.GetComponent<InvManager>().possibleItems.Length);
            item = invManager.GetComponent<InvManager>().possibleItems[randomIndex];
        }
        onCooldown = false;
    }
leaden ice
#

it's possible they want you to use Resources.Load or something, or possibly map the strings to prefabs with a switch statement or dictionary

#

kinda up to you I guess

lean sail
shadow nacelle
#

I'm aloud to fully change it but then I'm back at square one not knowing what to do

lean sail
# shadow nacelle yeah he basically made this code and made me think of a way to spawn the food it...

if you dont mind me asking, is this highschool? Im just trying to get perspective on if the teacher really doesnt know what they're doing, or maybe i am missing some additional context.
It's really weird that items would directly check the player Inventory to then add itself, and the name Inventory is quite misleading since its really just a "HeldItemName" or whatever you'd like to call it. And then theres other issues with your Table code.
The first problem you'll need to solve is having a way to reference the food prefab. You want to put this on a script related to when the item should spawn.

leaden ice
#

that's a very simple way for a beginner to think about this.

shadow nacelle
loud wharf
#

If ur teacher is a pretty unreliable source, YouTube might be better. :p

#

I know a guide that shows the basics in around ten minutes or half hour ish.
It's just a flappy bird clone.

shadow nacelle
#

anything helps

loud wharf
#

And that tutorial already shows what you need to do the task.

loud wharf
# shadow nacelle I would love the link ❤️

GMTK is powered by Patreon - https://www.patreon.com/GameMakersToolkit

Unity is an amazingly powerful game engine - but it can be hard to learn. Especially if you find tutorials hard to follow and prefer to learn by doing. If that sounds like you then this tutorial will get you acquainted with the basics - and then give you some goals to learn ...

▶ Play video
shadow nacelle
#

I will check it out

lean sail
# shadow nacelle and that would be for the 3 items I'm using?

you would do this for each item, to compare the name and then spawn the correct prefab. This script of yours is going to have to store a reference to all 3 prefabs.
Honestly I say you should do c# basics before unity, so you arent learning both c# and unity at the same time. Diving straight in unity is going to be rough

leaden ice
lean sail
#

although i know in your case itll probably be tough since your class is using unity

loud wharf
#

I stopped using Unity. UnityChanHelp

shadow nacelle
loud wharf
#

Try learning C# in free time? UnityChanHuh

shadow nacelle
loud wharf
#

It would suck to have been learning how to make a game and have the entire experience be rendered pointless.
Then again, that's how I imagine school to be anyways.