#💻┃code-beginner
1 messages · Page 30 of 1
@rich adder ok im back and it work but it only shoots up
can we see the whole error in console entire stacktrace and send the script not just a method
what did you change ? idk that
what worked
how would I check if this returns an object of type Item instead of just checking if it's not null?
if (_head.GetComponentInChildren<Item>() != null)
another thing to note is that being able to just yield an IEnumerator method call instead of being required to use StartCoroutine to wait for a nested coroutine to complete wasn't always possible
script?
oh its a new c# feature or something in unity?
void Shoot()
{
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
firePoint.transform.rotation = Quaternion.Euler(0f, 0f, Random.Range(-10f, 10f));
rb.AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);
}``` i changed ```cs
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, Quaternion.identity);``` to ```cs
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);``` and ```cs
firePoint.transform.rotation *=``` to ```cs
firePoint.transform.rotation =```
I never used IEnumerator outside unity context tbh
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
probably just a unity thing. there are posts from like 2015 asking why it wasn't possible to do that so the change happened sometime since then
pretty neat, I'm gonna look into it just curious 😅
did you try Debug.Log( destination_script) before print(next_location);
im trying right now ur Idea, but what do i do for mp3?
he tells me
UnityWebRequestMultimedia.GetAudioClip(path, AudioType.mp3)
does not work
because
'AudioType' does not contain a definition for 'mp3'
oh yeah that is the error
but would that cause me printing next_location to be null
spelling matters
your IDE is not configured is it..
you would see entire enum list when you do .
@rich adder
no thats something else
Configured to the database and stuff. Let's test out if mister chatgpt is correct
ah i see, mpeg
ok so destination_script is good but destination_script.target is null
Hey guys, im trying to get a mesh to correctly align with the player when aiming down sights, however when I walk away from the origin the rotation gets really messed up. can one of you guys take a look at my code and see what i'm doing wrong? (ill send the code as a seperate message if i can, its quite long and above the limit)
and here is a short video to demonstrate the issue:
here is the code:
private void LateUpdate()
{
var mouse_pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mouse_pos.z = 0f;
print(mouse_pos);
startingAngle = Mathf.Atan2(mouse_pos.y - transform.position.y, mouse_pos.x - transform.position.x) * Mathf.Rad2Deg;
print(startingAngle);
int rayCount = 600;
float angleIncrease = fov / rayCount;
float angle = startingAngle + (fov/2);
Vector3[] vertices = new Vector3[rayCount + 1 + 1];
Vector2[] uv = new Vector2[vertices.Length];
int[] triangles = new int[rayCount * 3];
vertices[0] = origin;
int vertexIndex = 1;
int triangleIndex = 0;
for (int i = 0; i <= rayCount; i++)
{
Vector3 vertex;
RaycastHit2D raycastHit2D = Physics2D.Raycast(origin, GetVectorFromAngle(angle), viewDistance, layerMask);
if (raycastHit2D.collider == null) {
// no hit
vertex = origin + GetVectorFromAngle(angle) * viewDistance;
} else {
//hit Object
vertex = raycastHit2D.point;
}
vertices[vertexIndex] = vertex;
if (i > 0)
{
triangles[triangleIndex + 0] = 0;
triangles[triangleIndex + 1] = vertexIndex - 1;
triangles[triangleIndex + 2] = vertexIndex;
triangleIndex += 3;
}
vertexIndex++;
angle -= angleIncrease;
}
mesh.vertices = vertices;
mesh.uv = uv;
mesh.triangles = triangles;
mesh.bounds = new Bounds(origin, Vector3.one * 1000f);
if (Input.GetKey(KeyCode.Mouse1))
{
fov = 60;
}
else
{
fov = defaultFov;
}
}
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
rb.AddForce(bullet.up * bulletForce, ForceMode2D.Impulse);
but also you can just cast the bullet as a rigidbody2D
Rigidbody2D bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
and skip the GetComponent
nvm destination_script.target is null because there is no target yet 🤦♂️
when I set a predetermined target it is valid
well yeah if you didn't assign it yet or assign it a null somehow
@rich adder Hey Honey, your Idea worked, at least in the Editor yet, get a digital Hug
:-]
ill try now on windows and mac, if that works aswell, imagine 2 more ;)
just make sure you're using the correct paths lol
@rich adder i get this error Error CS0029 Cannot implicitly convert type 'UnityEngine.GameObject' to 'UnityEngine.Rigidbody2D' on cs Rigidbody2D bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
bulletPrefab needs to be a Rigidbody2d to do that
yeah this sry
forgot to mention that
😅
might need to drag the prefab back inside the slot after
or unity gives a Mismatch
what do you mean
did bro just shot himself and died 
So i checked now, Windows works fine, but Mac dos noooot -_-'''
he can find the files, but he cannot play them
whyyyy
try removing the random rotation thing first, see if that fixes
how do you know the files are found
its the rotate line
playing from where tho also, a build or in editor
so they work fine without it ?
yep
i use
Directory.GetFiles
to find them, so i know, the Path is correct. Exept something in this www thing is changing the path, without me knowing o.o
try adding it to the euler angle instead
editor and windows build work fine, mac build does not, so 2 out of 3 Hugs
ideally you should have an onscreen debug / text showing what was found etc.
and which folder location are you using
Application.dataPath + "/Resources/Data/StreamingAssets/
for Mac
var rot = firePoint.transform.eulerAngles; rot.z += Random.Range(-10f, 10f); firePoint.transform.eulerAngles = rot; i think
bruh
you should be using Application.persistentDataPath
forget about the whole Resource thing too tbh
where is the difference?
but its said in the manual ...
macOS player uses Application.dataPath + "/Resources/Data/StreamingAssets"
it said ...
using Unity.Services.Core;
using Unity.Services.Economy;
using Unity.Services.Economy.Model;
using UnityEngine;
public class Economy : MonoBehaviour
{
string slurpCoins = "SLURP_COINS";
private async void Start()
{
await UnityServices.InitializeAsync();
await EconomyService.Instance.Configuration.SyncConfigurationAsync();
GetBalance();
}
private async void GetBalance()
{
CurrencyDefinition slurpCurrencyDefinition = EconomyService.Instance.Configuration.GetCurrency(slurpCoins);
PlayerBalance playersSlurpCoinsBalance = await slurpCurrencyDefinition.GetPlayerBalanceAsync();
if (playersSlurpCoinsBalance != null)
{
Debug.Log($"Player's balance: {playersSlurpCoinsBalance.Balance}");
}
else
{
Debug.LogError("Failed to get player's balance.");
}
}
}
Am I doing this correctly?
idk I don't use streamingassets, what was the point of doing HTTP then lol
https://docs.unity3d.com/ScriptReference/Application-persistentDataPath.html
gives you a consistent filepath not only inside the build
can someone help me? i need to access the durability from the item that is inheriting from item
this is my item script
https://hastebin.skyra.pw/iyinixefaz.csharp
this is my weapon type item script
https://hastebin.skyra.pw/ozokanoxes.csharp
so that i'll be able to use item.durability for example
item being this
so i tried this
persistentDataPath
but then i get an error with the www thing
i just want to load mp3 from streaming assets ... O.O
so max durability is on the weapon but item doesnt have durability, right
yeah
@rich adder i have to go but it goes in the right direction but doesnt start in the right angles
if you're trying to use the Streaming Assets folder, you should just use Application.streamingAssetsPath and not trying to construct the path manually
if you wanna use straaming assets then you have to use this
https://docs.unity3d.com/ScriptReference/Application-streamingAssetsPath.html
otherwise do it like i said with the HTTP local file
and some more item types are going to have durability
not just weapon
but its going to be a lot more
yeah but if he has a lot of different items of durability
like 10
weapon casting would fail on everything else
im not gonna cast and check like 10 things
oh yea like equipment items etc
thats pointless
mb
o.O interesting, ill try
or should i just put the durability into item?
then you could make Ibreakable interface and if item implements it that means it has durability
and save myself a lot of time
ok you can @ me if anything when ur back
idk tbh this class hierarchy thing is hard asf for myself but I got burned putting too much stuff into base class once XD
Well, that means everything has durability then
but then i can check like i did before
True
this is why I prefer usually using Interfaces over inheriting classes
much more modular
Am I on the right path?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
yea but so much more code
thats not the problem now in hindsight
but was main reason why I didnt like them bruh
much more code happens when your code is not split into single responsibility
usually
combination between both is best for me
it works so far in the editor, ill try in the builds now. if it works on mac, ull get the 3. Hug ;)
for?
Adding, removing curre by completing certain tasks in the future
its ok rn but you should put UnityServices.InitializeAsync(); inside its own class that has execution order before your other UGS calls
Okay thanks thats why i asked cus i wasnt sure what should be called first, etc
this way as long as that sevice is started, any other service like Economy will work fine
or if you need to login a user
if i started it in another script before this scene do i need to do it again?
iirc its per session and not per-scene
but im not 100% on that
I can test it later or you can try it or sum
yea il look
it will work but not well
it will just spawn bullet as child of pTrans
no specific position / rotation . just where pTrans is , as its child
if there is no log, the code is not running
it's not runniung
or the log would print
(I mean the code inside the if statement)
you are missing cs gamepadRight.action.Enable();
need to do that in Awake or Start or something
it does not work on mac. the files are found, as normal, but the sound is not heard
can i get the console into my build like
text.text = console;
?
as said before, you made the bulklet a child of pTrans. so... it's acting like a child
Is there a method for Unity.Services.Authentication; that u can use to sign out
Read this https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
Make sure you're using the right one
yes
depends on how you sign them in
Hey guys, im trying to get a mesh to correctly align with the player when aiming down sights, however when I walk away from the origin the rotation gets really messed up. can one of you guys take a look at my code and see what i'm doing wrong? (ill send the code as a seperate message if i can, its quite long and above the limit)
and here is a short video to demonstrate the issue:
private void LateUpdate()
{
var mouse_pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mouse_pos.z = 0f;
print(mouse_pos);
startingAngle = Mathf.Atan2(mouse_pos.y - transform.position.y, mouse_pos.x - transform.position.x) * Mathf.Rad2Deg;
print(startingAngle);
int rayCount = 600;
float angleIncrease = fov / rayCount;
float angle = startingAngle + (fov/2);
Vector3[] vertices = new Vector3[rayCount + 1 + 1];
Vector2[] uv = new Vector2[vertices.Length];
int[] triangles = new int[rayCount * 3];
vertices[0] = origin;
int vertexIndex = 1;
int triangleIndex = 0;
for (int i = 0; i <= rayCount; i++)
{
Vector3 vertex;
RaycastHit2D raycastHit2D = Physics2D.Raycast(origin, GetVectorFromAngle(angle), viewDistance, layerMask);
if (raycastHit2D.collider == null) {
// no hit
vertex = origin + GetVectorFromAngle(angle) * viewDistance;
} else {
//hit Object
vertex = raycastHit2D.point;
}
vertices[vertexIndex] = vertex;
if (i > 0)
{
triangles[triangleIndex + 0] = 0;
triangles[triangleIndex + 1] = vertexIndex - 1;
triangles[triangleIndex + 2] = vertexIndex;
triangleIndex += 3;
}
vertexIndex++;
angle -= angleIncrease;
}
Password and Name
I assume this does not have it
show GetVectorFromAngle(angle)
public static Vector3 GetVectorFromAngle(float angle)
{
// angle = 0 -> 360
float angleRad = angle * (Mathf.PI/180f);
return new Vector3(Mathf.Cos(angleRad), Mathf.Sin(angleRad));
}
how do I make the animation not start from the beginning of the scene?
could you help me?
i made the interface
dont make it your default start clip on animator
why are you doing angle * (Mathf.PI/180f);
looks good
if you want to convert to radians just do float angleRad = Mathf.Deg2Rad * angle;
and then on the item types that are using durability make then use the interface?
its from a tutorial but i think it converts to/from radians or smth
camelcase for public fields 😬
overcomplicated and pretty sure it's wrong
what do you mean
it should be Pascal case because they're public/properties
Yep
it's 180/PI not the other way around
but also just use Mathf.Rad2Deg
like i said its from a tutorial but this function is not wrong - its something to do with the code near the top of the script that is causing my problem
the fucntion is definitely wrong
To change from radians to degrees, you need to multiply the number of radians by 180/π
https://www.rapidtables.com/convert/number/radians-to-degrees.html
1 rad = 180°/π = 57.295779513°
Radians to degrees angle conversion calculator and how to convert.
pretty sure you copied it wrong @gray arrow
trying to compile my game, wont compile says its importing
when its not
tried restarting
nowt
i tried what you said and it completely destroyed the mesh
then you probably also have another issue elsewhere
If they log out and log back in the same account it wont create a new player id right?
using an incorrect conversion isn't going to make things work well
If im understanding correctly
nope
unless its anonymous
then i can do something like this?cs if(selectedCell.item && (selectedCell.item as IDurable).Durability > 0)
alright
@rich adder sorry to ping u but i wanna make sure i got this correct
anyone?
there is something wrong with the rotation of the mesh near the top, the rendering is fine trust me
I don't trust you because you started out with a wrong conversion from degrees to radians
not sure what ur doing exactly but looks fine
This is like that enum thing from before. Instead of having to check 100 different classes, you're chopping them into groups and checking by a set amount now.
Hey may someone help me
Im trying to do a Wave System where every 3 seconds a balloon spawns. The problem is unity spawns unlimited Balloons. Please help
oh alright
so im doing it correctly?
sounds like your code is bad
Try it :)
show script
How can i send it as an Code?
read the thing you summoned already #archived-code-general message
i dont think its wrong, heres what happens when i do as you say
like I said it just means you have some other issue in the code
nice, but did you test it in game
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class GameController : MonoBehaviour
{
[HideInInspector]
public List<GameObject> Balloons = new List<GameObject>();
public GameObject Balloon;
public GameObject Monkey;
public TextMeshProUGUI ScoreText;
public TextMeshProUGUI CoinsText;
internal int Score = 0;
internal int Coins = 120;
internal int MonkeyPrize = 100;
int WaveCounter = 1;
bool IsWaveActive;
void Start()
{
}
void Update()
{
ScoreText.text = Score.ToString();
CoinsText.text = "Coins: " + Coins.ToString();
if(WaveCounter == 1 && !IsWaveActive)
{
Wave1(10);
}
}
void Wave1(float WaveTimer)
{
while (WaveCounter == 1)
{
if (WaveTimer > 0)
{
IsWaveActive = true;
StartCoroutine(SpawnBalloons(Balloon, 3));
WaveTimer -= Time.deltaTime;
}
else
{
IsWaveActive = false;
WaveCounter += 1;
}
}
}
// Balloons spawnen und zur Liste "Balloons" hinzufügen
IEnumerator SpawnBalloons(GameObject Balloon, float WaitForSec)
{
while (IsWaveActive)
{
GameObject NewBalloon = Instantiate(Balloon);
Balloons.Add(NewBalloon);
yield return new WaitForSeconds(WaitForSec);
}
}
There are many things taken out. They are not important for the problem
start debugging things. What are the angles being printed etc
what are the vectors being produced
that's where you need to start
figure out where things go off the rails
things work near 0,0
but as you walk away they get bad
i think its to do with the mouse position being mapped to the world one
you are using a while loop when you should be using if
You mean in Wave?
If I have a block on a block on a block, and they are all dynamic, is there a way for me to stop the thing on the middle from being affected by the one on the top?
yes
Im going to try thx
I have to wonder if I would be better served by kinematic RBs for everything; but I don’t know how to manage basic collision with walls
you're also starting the coroutine every frame
which is probably not correct
it tells me
"cannot connect to destination host"
what does that mean?
Thank you very much it works now
Oh really? But it works
which line which one ?
probably something to do with HTTP? areyou still using that or streamingassets
now im confused
the Ingame Console you send me, gave me this notification (white), not as an error, but i think, that will be the problem.
ae you sure UnityWebRequest works on mac in the same way as on windows?
just because you can doesn't mean you should lol
literally creating a new coroutine each time
i have never used any internet paths. i am only using my streaming assets folder
sorry I mean UnityWebRequest
Where am i creating every time a new Coroutine?
you're not because of if (!IsWaveActive
i think that UnityWebRequest might not work in the same way on mac as on windows
your code was a little confusing so it's hard to see
ohh wops my mistake that also confused me
Okay thx
should probably make sure you're checking if item IS IDurable cause otherwise it will return null
I think you can just inline it there and get a reference? I forget
Noone has an Idea?
I want to use
UnityWebRequestMultimedia.GetAudioClip(path, AudioType.MPEG)
to load an mp3 from my streaming asset folder for my Audiosource but i get the Error
"cannot connect to destination host"
what happens?
if(item != null && item is IDurable durable) {}```
What path did you provide
yeah i forgot
i realised a minute ago
i did the same thing
works great thank you so much
ye np
Application.streamingAssetsPath
i now check chinese forums, cause it seems like they have the same problem xD
https://blog.csdn.net/Ailegen/article/details/105579247
关键字: Unity AudioSource本地Mp3文件加载UnityWebRequestMultimedia.GetAudioClip() 新版本api UnityWebRequest.GetAudioClip() 旧版api Errror:“Cannot connect to dest..._unitywebrequestmultimedia.getaudioclip
you can make this a little cleaner:
if (item is IDurable durableItem) {
}```
that's it? That won't point to an actual file, just the folder.
i can also now use interfaces for other specific item stats
if im going to have any
will that work?
depending on file
- "Subfolder" etc
you would also need cs file:// before it
since UnityWebRequest expects a URI
You still have to check the null though, no? Or will that not throw an error
i thought it would
funny, now i read this also on the chinese page
ill try
it doesnt
alright thanks
also, in case you aren't up to speed: the goal here is to produce an AudioClip from a file.
(possibly user-provided, hence being in StreamingAssets)
Yeah I got that part
although StreamingAssets isn't really the place for user provided files
it's the place for verbatim files from the project itself
i guess there's no reason for them to be in that folder in particular
since they just need to exist, somewhere
i hadn't actually thought about the point of that directory before
I did suggest earlier, at that point just use WebRequest + Application.persistentDatapath
dont think streamingasset is needed
chances are you're not passing the firepoint as spawn location @queen adder
hmm somehow they move as if they were parented to object
hard to say without seeing script
what does bullet scrit look like
hmm
Show the inspector for the bullet prefab
This is a step in the unity tutorial tha i am watching, i dont find the section "add modules", were can i find it in unity hub?
Gear icon on ur unity install
preferences?
oh thx
sorry i didnt see the video
yeah sorry, i read from up to down
so i respond to the first message and after to the second
i dont have that
this means you have not installed Unity from the hub
2021
that aint the issue, they have installed unity Manually
@rich adder I will be back in 20 minutes
with what ?
I thought u were sending bullet script
so bullet has no script
why do you have gravity in a topdown
set the Gravity scale to 0
it could if it hits colliders.
its an active physics object
ofc its gonna move
try without it or set it to kinematic
also your in Center pivot mode
not probably what you want to set up correct pivots
thi should be on Pivot / Local
it migt not even be spawning from where u think its spawning
yes
now make sure spawn points are where they need to be with correct rotations too
uh this wasnt a fix
which gameobject has BulletSpawn
screenshot it
with pivot selected
guys im trying to access the parent´s rigidbody of my object but this doesnt works,heres the code ```if (col.CompareTag("Toilet"))
{
Vector3 direction = col.GetComponentInParent<Rigidbody>().position - transform.position;
var m = col.GetComponentInParent<Rigidbody>();
float distance = direction.magnitude;
float forceFactor = 1f - (distance / explosionRadius);
float appliedForce = explosionForce * forceFactor;
m.AddForce(direction.normalized * appliedForce, ForceMode.Impulse);
var v = col.gameObject.GetComponent<ToiletBehaviour>();
v.isInFire = true;
}```
its not
show me with pivot selected
the MoveTool shows the pivot
select the movetool first
when I create item system using classes, where and how do I save a list of all possible items? do I have to create a c# script with a list of all items and its settings?
What "doesn't works"
ok the rotation at least is fdup , not sure why the position is wrong still though
thats cause you use Quaternion.identity
so, i have a class Entity with a child class Enemy
How can i know what Entity into a list are Enemy?
you did it. You earned the 3. Hug, that was the missing Part, thx :)
No, it's C# only
aw man
is there like some sort of plugin that can convert a c++ script to a c# script?
Likely not
if you already know c++ then c# is not that much more of a stretch
i get that but learning another language is just a hassle
Also, With Unity, Godot, Roblox and more utilising C#, It's a really valuable language to pick up
use Unreal 🤷♂️
Either use Unreal or learn C#, there's no shortcut
Although I didn't learn C# when I started Unity
my pc cant run unreal 😿
C++ similarities were enough to do most of the simple stuff
where can i learn c#
resources pinned in this channel
thanks
best of luck
"On the left of the Unity Hub window, select the Installs tab.
Select the Add button."
were is add? i dont see it
idek
didnt someone already show you this?
also why are u reposting it inside a code channel
i am following a link that someone sendend me and they literlaly said to follow it
oh, my bad
Whell, if you wanted to install a new editor, what button do you think might install an editor
#💻┃unity-talk lets use this chat
@rich adder are you here
yo
heres my current script https://gdl.space/acabojutit.cs
oh and the problem is that fire point is going all over and not resetting
@rich adder
Hi there! Does any one could help with a FPS that can move just with key forward and backyard and rotation left right (I have the code for the movement) with the collision? It's been 1 week I am trying to ads collision to my player.
yes it keeps changing
youd have to do some sort of timer / coroutine to snap back to original @violet topaz
it would be too instant without some smoothing but still doable
send script
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Thank you! I'm new here, what I am supposed to do?
If it's longer than like 10 lines, use one of the websites listed at the top
If shorter, you can use the inline code markup near the bottom
```cs
// Your code here
```
I see, let me try
I have never seen the ? operator in C# can someone explain to me this call one of my friends just submitted to our project's main branch? it seems to work i just don't understand it
equippedWeapon.Fire(aiming ? equippedWeaponScope.GetMultiplierSpread() : 1.0f);
@rich adder could i do if the firepoints rotation is > 10 and it resets back to zero
That is basically and inline if statement
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator
The thing BEFORE the ? Is the condition that would be in the if statement. The one between the ? And : is if that condition is true. The one after the : is if it's false
neat, is it any more efficient(at runtime not in terms of characters obviously)?
if you set it to 0 it will just look back up
I don't know. I think it's just convenience
if(rot.z > 10f rot.z < -10f)
{
rot.z = 0f;
} ``` how do i do "or"
you need to store the rotation before applying the Random offset @violet topaz
then apply it back
coolio, i still don't like single line if statements and always use brackets so i think i'm going to stray away from that but it's cool nonetheless
i could change it to the players look direction
using transform movement = no collisions
you're teleporting essentially
you want a character controller at very least
yes exactly
I don't want to use the mouse to move the camera
so don't
Thanks for the links!
I don"t know yet where to start
but hopefully Ill be able to add the missing code for the collision
look at this example
https://docs.unity3d.com/ScriptReference/CharacterController.Move.html
or make your life easier and use the premade one
https://assetstore.unity.com/packages/essentials/starter-assets-first-person-character-controller-urp-196525
Thanks you so much!
how can i pass a class by value instead of by reference?
@rich adder so you think a timer is the best way to fix my problem?
classes are not value types
possible, maybe a quick lerp
What is the use case? Could you make a struct and pass that? Structs are value types
ima take a wild guess, something to do with multiplayer xD
Thank you so so much! next time I will change the way it rotate... Thank you so so much again!
no probs 🙂 goodluck there
nop cause i need that class to have child ones
but anyway
i can still copy that class variable into a new one created with new() and i should be fine, right?
what is it you need to do this for?
so, when i do an attack in my game, i collect some info into a class called AttackData.
The Attack is a class (stored into a variable of enemy or player class) that contain some info, and i must pass an Attack into the method CollectAttackData. In this method, the Attack itself will be added to the AttackData infos as a variable.
The problem is that, later, i must manage and change some values of the Attack into the AttackData. But i don't want to change the value into the original Attack variable, that is still into a player/enemy
Hey, can someone help me with why my overlapsphere is getting every collider but my Player? im setting an array of colliders to the overlapsphere and then foreach collider in the array i debug the name but it never gets my player no matter how big the radius
are these not new instances of Attack?
or wouldn't attack just hold a struct for its data
do you have a layer parameter passed in ?
what exacly?
But i don't want to change the value into the original Attack variable, that is still into a player/enemy
ah thank you again it was driving me nuts
yeah
just store the struct of data
but i can't do a struct cause Attack is a class with some child class
and i need to pass the entire attack at the attackdata
huh ? what is the data you're talking about and why can't it be stored in a struct
i mean maybe i can create a struct into attack and just trhow all the infos of the attack into it..?
so, Attack have 2 child class: BuffableAttack and PlayerAttack, that have more infos of a normal Attack and override mostly every get property of the normal Attacks
and afaik struct can't have something like child class
maybe thats's what do you mean?
public class Attack : MonoBehaviour
{
public AttackData attackData;
}
[Serializable]
public struct AttackData
{
public int Data1;
public string Data2;
public float Data3;
}```
Only need to store AttackData no ?
[SerializeField] private List<AttackData> attackData;
[SerializeField] private List<Attack> attacks;
private void Awake() => attacks.AddRange(FindObjectsOfType<Attack>());
private IEnumerator Start()
{
yield return new WaitForSeconds(2);
foreach (Attack attack in attacks)
{
attackData.Add(attack.attackData);
}
for (int i = 0; i < attackData.Count; i++)
{
var ada = attackData[i];
ada.Data2 = "Hellooooooooo";
attackData[i] = ada;
}
}```
AttackData is a different class, that contains more info other then the attack. The attack must go INTO the attackdata
idk working with reference types is annoying sometimes with that
yeah i can think at something like that, store the only infos that AttackData needs into a struct
all your doing is passing around copies of the same pointer
I will see tomorrow. Thanks!
How can i make remember me check box for login using UGS with name and password identity
the copy stays put and doesn't affect original
like i cant figure out any way
without storing the login in prefs or locally
You can't without doing that
Or some data locally
thats the default
and also they dont store login
its a session token
also don't crosspost lol you already asking multiple channels #💻┃unity-talk
im not i just didnt care about that question anymore lol
https://paste.ofcode.org/4CTDzchhHWhbyKVZ2wnL4n
I don't know what I did wrong here. There are console errors:
Assets\SceneManager.cs(10,22): error CS0117: 'SceneManager' does not contain a definition for 'LoadScene'
Assets\Scenes.cs(10,22): error CS0117: 'SceneManager' does not contain a definition for 'LoadScene'
I looked through it on the forums they said to not have the public class set to SceneManager, however I changed it to Scenes along with the script name but it still does not work.
You have your own class named SceneManager
Which is apparent from:
Assets\SceneManager.cs(10,22): error CS0117: 'SceneManager' does not contain a definition for 'LoadScene'
ah rip
it's trying to use YOUR class instead of Unity's
didnt even notice script name lmfao
you can fix this by doing UnityEngine.SceneManagement.LoadScene - or by renaming your class, or with a using SceneManager = UnityEngine.SceneManagement.SceneManager;
I chnaged the class to Scenes
It maybe looks like you tried to rename the script but actually you duplicated the script
the old one still exists
hence that first error
You're right, One script is named Scenemanager and one is Scenes
are you trying to say here using UnityEngine.SceneManagement.SceneManager or something else?
No, they meant meant it the way it was written. The = sign to declare the expected qualifier to prevent ambiguity
using SceneManager = UnityEngine.SceneManagement.SceneManager;
The way you have it written wouldn't work, it would still be ambiguous
It might show a different error though
you shouldn't have to worry about it tbh just call your script something else lmao
I got that part working now, my only problem is that I don't see the funtion on the button (I don't know how to explain it)
Yeah, never name a class the same thing as a built in class unless you REALLY know what you're doing and know your way around namespaces. And even then, probably don't
probably because you dragged the script from the project folder and not the gameobject its on
unless you still got compile error lol
I Did it through add component
I don't
the button, show where its not showing up
Did you delete the SceneManager script you had?
yes I deleted both andjust pasted back the info in a new script and it works
Ok, show a screenshot of showing the buttons inspector
Not an object
yes
It would show "(objectName)"
Unless I'm misremembering
and you did not drag script from said object
I dragged the gameobject and it works
how do you get the height of a mesh at a certain point
use the collider on it
I have tried, i might have done it wrong so how would you do it
show what you tried
Sorry for responding late, I'm doing that if my object is close to an explosion it moves a little but the thing that doesn't work is because the collider is in the child object (the object is already selected) and the rigid body in the parent
I'm trying to say exactly what I said
it won't get the point, it just gets the mesh position
Have you tried just raycasting down and getting the position of the raycastHit?
You can even use my favorite underrated function:
https://docs.unity3d.com/ScriptReference/Collider.Raycast.html
Note this is Collider.Raycast, not Physics.Raycast
I have tried regular raycasting and it returns a distance of zero
I have not gotten collider.Raycast to work
i have tried physics.raycast as well
that did not work either
should also do Gizmos.DrawSphere(closestPoint, 0.1f);
Can you show us the mesh and the sphere in question?
is the sphere inside the mesh?
I promise you it does work. Show what you did?
meshObject = new GameObject("Terrain Chunk(" + regionX + ", " + regionY + ")");
that tells me nothing about the mesh
that's just a GameObject
an empty one at that
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
@slender path Can I get some context for those massive dumps of code? On a quick look, it seems like you don't add the mesh anywhere between line 55 and 66 on that first script?
for a simple 2D top down game, should i use transform.Translate, rb.MovePosition er whats best
if you want accurate collisions use rb.MovePosition
neither of those will give accurate collisions
If you want proper collision handling you must move via modifying Rigidbody velocity or by adding forces (which modifies rigidbody velocity)
as long as the collisions are ok its fine
there is no "best". It depends on the game.
this game is more of an animation learning process
so for a more accurate game i should use this?
depends what you mean by "accurate"
lots of games don't require physics at all. For example grid based games
oh..thought Kinematic character controller used rb.MovePosition with kinematic
yes it can but kinematic aren't affected by collisions with anything
oh yeah it probably does ray/physics casts for collisions
'
see above, i'm following a tutorial for 2d movemen, but for some reason my character always gets triggered by a collision i cant discover.
as you see in the video the layers are correctly placed, and character movement is smooth, except for some certain spots where it gets stuck
would be apprecated with any feedback
Ok so Im trying to make a system where these "obstacles" spawn along a road at random points on that road. For some reason when I run this script on an empty object (properly assigning the public variables), the obstacles only spawn on one point.
does anyone know how to fix this
I even tried this simplified version but it still wont spawn in diff places.
Note: i used a sprite (which is a long rectangle) as the road, assuming that the objects spawn along that road
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
you're just spawning them all in the same place?
where are you adjusting the position?
The spawn object on road function picks a random point
Im not sure if this is the right channel but Im dying for some help!
Im trying to open a unity package file of a vtuber but it wont open? or at least when i import I see absolutely nothing does anyone know how to fix this?
it doesn't really, it seems to pick a random number between 1 & 9
There is nothing in the scene, or nothing in the project window?
Ill be honest I have no clue what either of those are (i literally just downloaded unity to open this) but I assume the project window is the main thing Im looking at and I see nothing there
Try putting some Debug.Log() on your spawn locations
The project window is the one on the bottom by default and has files and folders and stuff.
It has the word "Project" over it
also there is a thing saying for me to check external application preferences and its unable to open the asset
I see the stuff I imported in the project thingy under assets
Maybe take a screenshot of the whole unity editor as you see it now
Heres the screenshot ^
Are there any other scenes here?
Hmmmm alright
What is the package SUPPOSED to have?
It seems to have a model with its associated texture(s) and material(s)
Is there supposed to be more?
oh...
shit...
I just realized I only downloaded the hair of the character...
I appreciate your time
I will grovel in my stupidity now
welcome to programming 🙂
pretty much what we do most of the time
That certainly helps my mood rn I spent way too much time trying to figure this out before coming here..
won't be the last time 😉
What is the proper syntax for this? Item is a Script
if (_head.GetComponentInChildren<Item>().GetType() != Item)
Or can I just check if it's not null since it should always be of type Item anyway?
You don't need to get the type if you are just trying to figure out whether the 2 item instances are the same instance
What is the goal here?
Attaching IDs to Item and comparing those can be used to differentiate between different items that are represented by the same Item type.
okay im making another attempt at opening at different model package (its actually the model) and it still wont come up
what are you trying to do?
seems like you should do some basic unity tutorials first, so you actually know what's going on?
there should be some in the pinned messages
just want to make sure that a child Item exists
I want to open up different models then Ill convert them to vrm so I can use them for my stream
I figured since im just trying to open stuff and convert them I didnt need to but you may be right here
plus all the videos I looked they just opened right away for others
this doesn't look like code though, i'd try #🔀┃art-asset-workflow or #💻┃unity-talk
Thank you apologies!
Why are there green + icons on my item prefabs but not on my itemslot prefabs?
I don't see any overrides
means you added something new to the ItemSlot prefab that isn't on the original prefab
I just dragged the prefab into my hierarchy though, so how can there be something new?
is it because it has a different parent?
its letting you know you added Item as the new element to ItemSlot
hmm kaj
how do i set fullScreenMode? i literally can not find info anywhere, only for fullScreen
for the build?
im new and i just want to learn how to code, is learning on youtube or docs better
structured course + docs + lectures
There are resources pinned on this channel. Unity's courses are good. I like the c# course from W3Schools too
Ok, thx guys 👍
I've seen a lot of ppl recommend you just follow 3 full guides on easy games and then start from scratch on your first own game without tutorials
tutorials are great for getting familiar with unity and learning what's possible
but they're terrible for actually getting better at building your own games
why might i get an out of range exception when i call any index in an array?
the array is smaller than the index you are providing
it has 2 values, i call 0 and 1
show the code
public void SetWindowMode(int mod)
{
if (mod == 0) Screen.SetResolution(res[0], res[1], FullScreenMode.ExclusiveFullScreen);
if (mod == 1) Screen.SetResolution(res[0], res[1], FullScreenMode.Windowed);
else Screen.SetResolution(res[0], res[1], FullScreenMode.FullScreenWindow);
mode = mod;
PlayerPrefs.SetInt("WindowMode", mod);
}
public void SetResolution(int reso)
{
if (reso == 0) res = new int[2] { 848, 480 };
if (reso == 0) res = new int[2] { 1280, 720 };
if (reso == 0) res = new int[2] { 1920, 1080 };
if (reso == 0) res = new int[2] { 2650, 1440 };
else res = new int[2] { 3840, 2160 };
resolution = reso;
PlayerPrefs.SetInt("Resolution", reso);
SetWindowMode(mode);
}```
god damnit
nevermind
i called setwindowmode before set resolution
yeah that'll do it. also what's up with the 4 identical conditions? you do know if that condition is true only the last one will matter. and you're allocating 4 arrays for it but then only using the last one
i realised that also
now im getting an out of range error with a dropdown menu when i try set its value to 4, it has 5 options so i dont get it
show the code 😛
volume = PlayerPrefs.GetFloat("Volume");
mode = PlayerPrefs.GetInt("WindowMode");
resolution = PlayerPrefs.GetInt("Resolution");
Debug.Log("v " + volume);
Debug.Log("m " + mode);
Debug.Log("r " + resolution);
modDD.GetComponent<TMP_Dropdown>().value = mode;
resDD.GetComponent<TMP_Dropdown>().value = resolution;
volS.GetComponent<Slider>().value = volume;```
i can see in the log that resolution is set to 4, the dropdown object has 5 options
which line is throwing the error?
a line in the TMP_Dropdown script
you have two TMP_Dropdown here
yeah
i get the error for the resolution dropdown but not the mode dropdown
if i remove the = mode from the script then the resolution one works...
what
are you sure you're setting the correct dropdown component?
yeah
can you drag and drop the reference of tmp dropdown to your script component? it is safer, an log the length of options of tmp dropdown
yeah when i log the options count it says 5
wtf i just swapped the order so it sets resolution then mode and now it all works??
is this a unity/tmp bug?
most likely what happened was after the first change you made you saved the code and whatever was initially causing it had already been fixed and was finally compiled
unless you are doing something in one of the OnValueChanged events that is causing the issue
i just changed the order back and it broke again
then it's probably something you are doing in OnValueChanged
of course you haven't even provided the stack trace, or even the actual error message for that matter. so it's hard to tell
The only two reasons it could happen are some code running on the value being changed as box said, or a very reliable and specific race condition. The latter is incredibly unlikely (honestly probably impossible), so it's probably the former.
i see, it was the same index out of range error as i was having before but when i clicked the error message it took me to a line of code in the TMP_Dropdown script
show the stack trace
I just set up a slider in my project, but when I try to interact with it, I always just interact with the object behind the slider. I have already searched the internet for solutions, but nothing I found there worked.
is this stack trace
and what is line 46 of SettingsMenu.cs
ty
that is where i set the resolution, its the same error i had before
and let me guess, that method is being called in OnValueChanged, yes?
indeed
can you share the entire script in a bin site so we can get an actual understanding of what exactly is happening in this code
why? i already solved it
You did not
You need to know why it happened to solve it, otherwise you're just masking the issue
a
that's a bandaid fix at best and does not actually solve the underlying issue
^
that was when i figured it out, its because when i set the value it called something that isnt supposed to be called first
What object was being indexed
an int array for resolution
do you want to actually solve this? or would you rather go with your bandaid fix and have to make sure that you always do things in a very specific order and potentially run into this issue many times in the future?
So modDD.TMP_DropDown.OnValueChanged indexed an array for resolution?
That's a little odd
Does it index it using the value in the resolution dropdown
the resolution dropdown creates an array with the resolution height and width and then mode uses it to set the actual resolution and window mode, if i call mode first there is no array yet
i didnt realise setting the value in script called onvaluechanged
Why does the dropdown create an array?
How are the array values tied to the currently select value of the dropdown?
b
it does because that event is invoked every time the value is changed. there is a SetWithoutNotify method on the TMP_Dropdown class though that you can use as another sort of bandaid fix
you realize this does not answer why
you mean like why did i personally do it this way?
yes. you're also hardcoding these values for some reason instead of getting the available options that the device supports
idk breh it was was the first thing i thought of
well if you were to get the available options using unity's API then you could create the relevant arrays and cache them before either of these methods are called. although you don't even need arrays, just use a Vector2Int or even just two ints since you're just storing 2 ints and using them individually instead of using the array for anything
Hello just a quick question about this error im getting. Im trying to do
Debug.Log(tileManager.GetInstance().columns + " " + tileManager.GetInstance().rows);
Debug.Log(newUpdate[0, 0].currentState);
but its telling me that the debug.log for newUpdate[0,0] object reference is not set to an instance of an object?
that means you have created the array but not actually assigned anything to that position in the array
the default value for reference types is null
you just create the array of reference but no any instnace is referenced
oh... so just foreach loop through and give it a tile?
not a foreach since that wouldn't work. but for loops, yes
ah ok thanks ;-;
Hey guys I was wondering if I could get some help on my 2D jump.
So my jump is currently FPS dependent, I tried countless ways to fix it but I just couldn't, can you guys help me?
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
you're calling HandleJumping in Update and adding continuous force to the rb
yeah...sorry but I don't really see what the problem is it keeps adding force until jumpTime is less than 0 and then stops
yes, you're adding force every frame for that duration
this is why your jump is framerate dependent. you would want to do that inside of FixedUpdate not Update
but you also cannot use GetKeyDown and GetKeyUp in FixedUpdate because those are only true for a single frame. so you need to split it up to get the input in Update and apply the force in FixedUpdate
oh, ok I'll try it give me a sec tysm!
Yo can anyone help me out here? I got these 2 balls - you can pick which one u want to use (coop type thing) And for some reason it doesn't let me ground check. atm IsGrounded() is constantly true whether you're above the range or not - IsGrounded() method at bottom https://gdl.space/gesefuguva.cs
now it works it's really weird because I tried it before, didn't know I had to get the input in update and then apply the forces in fixed update because the sprinting part worked fine but thank you a lot, you really saved me a lot of time
it sounds like you may have a collider on one of the layers in the layermask somewhere you don't expect it to be or your groundSquare is much larger than you expect
oh another possibility is you've selected the wrong transform for the groundCheck object or it isn't actually attached to the player
Ok, I created a gizmo that relates to the size of that box and everything looks alright
and after disabling all 'jumpable' layers from all objects, I can still infintely jump for some reason
The groundcheck objects are correct in the inspector
what layer(s) are the player's collider(s) on?
as in the player object? or the collider of the player
any object attached to the player that has a collider
bc currently the objects are on no layers at all and I can still jump
including the player object itself
all are on default
all of them including the player
I dont think its a layer issue
- Still infinitely jump
That is the player 2 ball
Is it an issue with the overlapbox? It was working correctly before I changed it from an overlap circle to a box
change your IsGrounded method to this and show what it prints:
public bool IsGrounded()
{
var hit = Physics2D.OverlapBox(groundCheck.position, groundSquare, LayerMask.GetMask("Jump", otherPlayer));
Debug.Log($"{hit.name} was detected by the OverlapBox. It is on layer {LayerMask.LayerToName(hit.gameObject.layer)}");
return hit;
}
But I can't see reason to not allow it to be a box
ok
Upon using the player 1, ground and player 1 was detected
(The true statement is a debug.log saying its grounded
oh whoops i forgot to add a check to make sure it doesn't try to print when nothing was hit
Upon switching with characters, and jumping, it says the player I jumped with was detected
Oh ok
looks like your player and ground are on the same layer
Oh yeah, Ill change that real quick
yeah it's kind of the whole issue. if the player is on the layer you are checking for ground and then its collider will be considered ground for your OverlapBox
I see
I imagined that the 'other player' string where I input the layer string of the other player would fix that tho right?
if the player is on any of the layers that are included in the layermask then it can be detected by the overlapbox
I also unset the jump layer in the inspector
So there was no layers active for the code to read
and it still jumped infinitely
and is the log still printing that it has found something?
Yeah
"Ground was detected by the OverlapBox. It is on layer Default"
Oh wait a minute
public bool IsGrounded()
{
var layerMask = LayerMask.GetMask("Jump", otherPlayer);
var hit = Physics2D.OverlapBox(groundCheck.position, groundSquare, layerMask);
if(hit)
Debug.Log($"{hit.name} was detected by the OverlapBox that originated at {groundCheck.position} with size {groundSquare}. It is on layer {hit.gameObject.layer} ({LayerMask.LayerToName(hit.gameObject.layer)}) at position {hit.transform.position}. Other layer to check: {otherPlayer}. {layerMask} ({GetInstanceID()}).");
else Debug.Log($"No ground detected this frame ({GetInstanceID()})");
return hit;
}
try that and show what it prints
no definition for hit.gameObject.Layer it says
think i got it
lowercase l on layer yeah?
whoops hit shift on that my bad
i made one more change to the log can you copy/paste it again and show what it prints now?
Hey, can I delete one of these? They are causing multiple ambiguous reference errors.
delete the second as you are probably not using UIElements. you would know if you were
Yeah, VSCode added it on it's own
oh wait, you're also calling IsGrounded like 5 or 6 times per frame. you should start by caching the result of that at the beginning of Update instead of calling it that many times per frame. it will not only save a bit of performance, but your logs won't be littered with so many of those calls. because right now you're screenshotting fewer logs than you are printing each frame
Alr
after you make that change you should post your updated code so i can take another look at it
ok I'll be back later bc i gotta head out for now
Ill try that when im back in
thanks tho man
Hey guys! I need some help with my code. Im trying to do a Tower Defense Game. Ive build a Wave System but it doesnt work that quite like i wanted too. The WaveTimer gets at the start once with 9.98 Debug.Loged. So the WaveTimer doesnt work. Maybe someone can help me.
Where are you delcaring WaveTimer or am I blind ignore this just woke up ;)
the tutorial that i am following is using the "Istantiate", but when i try to use it i get an error, why?
Spelling
what do you mean?
You are missing an N
Look at the red line
Your IDE would suggest a fix if you would hover over the error.
Ok I think I may see the problem and it's that you don't use a member value as the time counter
and because you send it into the function, it's a value type and not a reference type (basically it creates a duplicate of the value and passes it into the function)
so updating it and sending it back in won't change
my ide said "istantiate dont exist", i was thinking it was because the tutorial is old
So i need it to be a variable at the top right?
That would be the easiest idea here, and you can reuse it.
Yeah, and below that, it would suggest a fix probably.
Wave1 and Wave2 are only called once so there is no timing function going on there
Could also make a single wave function as well.
and just give it different parameters, but yeah it's only being called once
next time i will see, thx for the advice
So i put a variable at the top.
WaveTimer stays at 9.98 and not more.
Hey, is Vector3.forward relative to the object's rotation?
But they are called in Update
yes, only once
Why? WaveCounter is one and stays at one for the moment
Ahhh because of !IsWaveActive
exactly
Okay. What exactly can i do about it? Im not advanced sry
make Wave1 and Wave2 Coroutines and loop within them
Could kinda just remove that check completely since you are also checking the wave number
You mean a while True?
Which check?
I was thinking more like a while Wavetimer > 0
Got it! Now i need to return sth. Or there would be an error
you've made coroutines before so you should know how they need to work
Yeah! I need to to WaitForSeconds. But why do i even need a Coroutine here?
you dont need waitforseconds and you need a coroutine because you want it to loop but not block
Nope it isn't
Sry but then i dont know exactly what all things I can do with Coroutines. I just know WaitForSeconds
that is why Unity wrote documentation so you can reference it
This is another acc because my main got disabled ..... Probably because I was joking around I was underage in another server
Nope it stays in one place but the spawn point is way of
Anyways it would be great if you would reply
How do you give something like AddForce to a Character Controller? Move just teleports around.
You need a rigidbody, google, there are looooads of tutorials etc.
I though it wasn't compatible with CC
Oh, the character controller component is already a rigidbody of sorts. Have a look for chracter controller tutorials.
Thanks, I'll have a look tomorrow, it seems a bit complicated to do
It's really not.
Maybe but everything is complicated when you need to sleep lol
Im really sry but WaitForSeconds and return null is not working. I read the documentation and I am not sure what there could help me.
@fair steeple
I found this one to be really good. Covers a lot of stuff, but just pick and choose.
https://www.youtube.com/playlist?list=PLfhbBaEcybmgidDH3RX_qzFM0mIxWJa21
just use yield return null
inside your while loop
Oh neat, there's some stuff that I will need later too
Well cya and thanks for the help, I really need to sleep
Oh sry i put it in the wrong line. That wont happen again.
Now the last problem is that there are many balloons spawning and not one every 3 Seconds
is there any way to see the console in android? To see logs and that kind of things
so your StartCoroutine(SpawnBalloons needs to be before the while loop in Wave not inside it
{
int WaitForSec = 3;
if(WaveCounter == 1)
{
StartCoroutine(SpawnBalloons(Balloon, WaitForSec));
}
while(WaveTimer > 0)
{
if (WaveCounter == 1)
{
if (WaveTimer > 0)
{
IsWaveActive = true;
WaveTimer -= Time.deltaTime;
Debug.Log(WaveTimer);
}
else
{
IsWaveActive = false;
WaveCounter += 1;
}
}
yield return null;
}
}``` Like that right?
Look at your code and think about it
I dont see a mistake in here
not a mistake as such.
Under what conditions is Wave1 started?
if WaveCounter == 1 and IsWaveActive == false
right so why are you testing WaveCounter again. Not once but twice?
Twice is pretty dumb yeah. Im testing it to see which wave right now should be activated
but it can only be 1 because that is the condition for starting it in the first place
At the start it is one but at the end of the function it shouldnt be one
irrelevant
Ahhhhh
The while can only be activated if WaveTimer is above zero. So in that case there cannot be an if WaveTimer is under zero
yep, the else code should be after the while is complete
Okay that works. It changes to two. But the Balloons still dont get spawned
think about it, under which conditions do you Spawn balloons and when is that condition set?
if WaveCounter == 1. That doest make sense because the Coroutine only gets started when its 1. So i deleted that. Now the Balloon Coroutine gets started when the Wave Coroutine starts
yes, but the condition within the spawner is not being met because you are setting it at the wrong time
So IsWaveActive needs to be true before the BalloonCoroutine starts
Thats true. Im trying out wait
It is working but there is still one last problem. After Wave1 The Balloon and the TestBalloon get spawned. I dont want that. I only want that TestBaloon gets spawned
now why do you think that is?
exactly, so when you Start the SpawnBallons coroutine save the return value and use a StopCoroutine with it at the end of Wave
I have a button that is calling a script on my Menu object
Can I somehow pass a component of the button to the Menu script?
Button events allow you to pass a single parameter, no? I forget
Why do i need to save the return?
because you need it for StopCoroutine
ah yeah 🙂 ty
And how do i safe the WaitforSeconds return
You can also pass in a delegate if you need to if you can't pass the type/ref value. Make like a delegate getter
not waitforseconds. The return value from StartCoroutine
So Balloon and WaitForSeconds?
no. Do you not understand what return value means?
You can return values and save them in a variable. The only return we make is WaitForSeconds, and I dont know why we need that.
when you call a method and StartCoroutine is a method is can return a value.
In this case StartCoroutine returns a value of type Coroutine
int MyMethod() { return 1; }
returns a value of type int containing the value 1
So we return a IEnumerator
Iam so dumb. I was the wole time on a wrong documentation. We can stop the coroutine by yield return null;
omg
Coroutine cor = StartCoroutine ...
...
StopCoroutine(cor);
What am i missing? why is there no UnityEngine.UI documentation?
Yes now it works. Im sry that I didnt understand you. Thank you
show me the code you now have for Wave1
{
WaveTimer = 10;
int WaitForSec = 3;
IsWaveActive = true;
Coroutine cor = StartCoroutine(SpawnBalloons(Balloon, WaitForSec));
while (WaveTimer > 0)
{
WaveTimer -= Time.deltaTime;
Debug.Log(WaveTimer);
yield return null;
}
IsWaveActive = false;
WaveCounter += 1;
StopCoroutine(cor);
}```
perfect.
Now one thing for you to think about
The only difference between Wave1 and Wave2 is the GameObject being passed to SpawnBalloons. So why not pass that as a parameter to Wave then you only need 1 Wave Coroutine
Thank you. Thats a pretty good Idea. Then I am renaming Wave1 to WaveSpawner and then i can make many functions that are small and they all go to Wave 1
exactly, you've got it
Thanks
Any idea what could cause this?
It just randomly starting happening when I run my game, doesn't break anything though and I got no idea what caused it
Unity Editor bug. Restart Unity
I think this only happends when having selected a scriptable object
It's just annoying
Does not affect the game
kaj cool thx
[SerializeField] private GameObject _shoulders;
[SerializeField] private GameObject _body;```
I want to replace ^ with the array below, but can't seem to find the correct syntax
Is it possible to do this? I need to assign all the gameobjects in the editor
`[SerializeField] private GameObject[] itemSlots = {"head", shoulders };`
ah nvm
[SerializeField] private GameObject[] itemSlots;
and then I can just assign as many fields as I need
ye, it will extend the array like a list in the editor if needed
Hi all,
Would anyone please take a look at the vid and code and tell me what I'm missing please, been trying to figure this out for about an hour. lol.
Basically I'm trying to write a really simple script so that the suspension rotates to meet the wheel.
Wheels are controlled with NWH's wheel controller asset, now the annoying thing is that the angle of the suspension arm is matching the 'calculated' angle (from the suspension arms origin), but it doesn't seem to be correct and I'm completely baffled.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
hi, i am following a tutorial to learn unity ( https://youtu.be/XtQMytORBmM?si=N0uFeL49lJdUppGs ), i am making flappy bird with unity, the tutorial did something that i didnt understand very well, can someone pls explain?
this is the part:
Instantiate(pipe, new Vector3(transform.position.x, Random.Range(Lowest,Highest), 0), transform.rotation);```
in the tutorial he use this part to spawn the pipes, but i didnt undertand how to use it (i just copied)
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 ...
What do you not understand about that? Which function do you not know?
Instantiate creates an instance of the game object you put in
new just indicates that you're introducing a brand new Vector3 which is being defined then and there
maybe is a stupid question but, my game is 3d, why do i need a 3d vector?
Do you mean that your game is 2D?
Unity is p much built around 3D so a lot of the functions expect 3D Vectors, but usually you can put something like 0 or 1 for the z value
oh ok
so i am creating a new vector and the moving only the y position right?
because the first one is with the trasform.posizition, and z is 0
yes
That particular Vector3 is deciding where you want to place the object you're going to instantiate
👌
I want to test OnGameOver function that has 11 references, specifically the IsGameOver bool and the reason var, how can i test for that while disregarding stuff like SpawnUIScreen and gameobjects? do i have to comment it out or something? should i find a way to separate it?
you can comment/uncomment a bunch of lines of code pretty fast by selecting them and doing Ctrl + K, then Ctrl + C to comment, Ctrl + U to uncomment
Ok TIL
float Lowest = transform.position.y - Altezza;
float Highest = transform.position.y + Altezza;```
also the tutorial made me create this using the variable `Altezza` that has a value of 10.
after i used lowest and highest in:
```csharp
Instantiate(pipe, new Vector3(transform.position.x, Random.Range(Lowest,Highest), 0), transform.rotation);```
why i did this and i used the variable `Altezza` and not just a value for lowest and higest?
what if i want to use Nunit? like i want to still test for them if more code/logic is added
you want to create UnitTest no just test your code ?
yeah
Unity have their own test framework : https://docs.unity3d.com/Packages/com.unity.test-framework@1.3/manual/index.html i don't know if that can help you but i don't know if use Nunit is possible in unity
apparently their test framework is a version of nunit
so is perfect ^^
huh, why would you test in edit mode and not play mode?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MidleScript : MonoBehaviour
{
public LogicScript logic;
// Start is called before the first frame update
void Start()
{
logic = GameObject.FindGameObjectsWithTag("Logic").GetComponent<LogicScript>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
logic.ScoreUpdate();
}
}```
i get an error on `.GetComponent<LogicScript>();`
if you need to load gamemecanic like gravity
So you have a offset and can adjust it, and more readability ig
so you use it for a more strict environment ?
here you have inventory test in edit mode, i don't need to load scene, and in playmode you load the scene and verif like NPC path
what do you mean sorry?
ah so play mode is for something integration or system testing
I need help
try using FindGameObject, not Objects
i think you use just Find? or is it not a child
thx, i used "tab" without looking
Because if you want to change the number to, say, 11, you only have to change one number
In my game I created a transition in the start menu but it always plays behind the buttons and not in front of them. What do I have to do?
for the y value on your script when instantiating a pipe, you are choosing a random value between the value of the variable Lowest & Highest, the Lowest var is the transform.position.y of the object that has the script attached - Altezza and Highest is the same but + Altezza, so you get a range of values in wich the pipe could be instantiated, you use your variable to create that "space" or "offset" or whatever you want to call it, and use a variable so you can quickly adjust it and make the code more readable
FindGameObjects returns an array so that why you were getting the error when trying to get the component
yo, im very new to unity and trying to get a very simply stationary turret working
when the i use the arrow keys, the turret is supposed to rotate left and right whilst remaining stationary
but im getting this:
the turret moves from the base
heres my script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rotation : MonoBehaviour
{
public float rotationSpeed = 50.0f;
void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
transform.Rotate(Vector3.up * horizontalInput * rotationSpeed * Time.deltaTime, Space.Self);
}
}
In you UI order the bottons are on the top of the animation, try changing the canvas sort order in the inspector
but how
and my hierachy:
the script is inside my base parent file (the drop down one)
i tried switching it and doesnt change anything
any help would be great
Is the fade animation inside a canvas?
no
Its a image?
🤟🏻
is the script on the turret or in the base?
it was in the gun section, which was inside the base parent
ive fixed it its ok now
thank you
i had my parenting a little weirf
weird that was all#
hi guys, I need a simple answer for this one:
I want to use trig funtions, but I need an angle in either degrees or radians to do so.
how do I convert a 2D sprite's rotation quaternion into an angle float?
its probably a one-line-of-code thing, but im too bad at coding to do it lmao
get the sprite rotation, convert from quaternion angles to euler angles, then convert it from degrees to rad using Mathf.Deg2Rad
// 1. Get the sprite's rotation Quaternion
Quaternion spriteRotation = spriteTransform.rotation;
// 2. Convert the Quaternion to Euler angles
Vector3 spriteEulerAngles = spriteRotation.eulerAngles;
// 3. Extract the angle you need (in degrees)
float rotationAngleDegrees = spriteEulerAngles.z;
// If you want the angle in radians, you can convert from degrees to radians
float rotationAngleRadians = rotationAngleDegrees * Mathf.Deg2Rad;
cheers man 👍🏻
I've been trying to fix my collisions for 2 hours now and I have no idea why it doesn't work. Can someone help me please ? On the first picture there are properties for objects and on the second one for the player.
You don't need to convert anything. You can access the eulerAngles of the rotation or the transform using transform.eulerAngles or transform.rotation.eulerAngles. Then select the axis you want to use . . .
hey I'm new to unity what are my opportunities to get the world map into the editor?
I want to build a strategy game
What do you mean by doesn't work
does the interface look correctly?
so then i can do something likecs (inputItem as IDurable).Durability = (inputItem as IDurable).MaxDurability;
can i make this any simpler?
or is it alright
If you're referring to OnTriggerEnter or OnCollisionEnter stuff, see pinned messages. Look for Physics messages under Troubleshooting
Uh i have a MonoBehaviour that has an public UnityEvent MethodName; and a method called MethodName in that MonoBehaviour:
public class Class : MonoBehaviour
{
public UnityEvent MethodName;
// Error: Class already contains a method named "MethodName"
public void MethodName()
{
}
}
How could i accept both of them?
Name the variable something else?
Any other solutions?