#archived-code-general
1 messages Β· Page 98 of 1
Thanks thats probably it, so my second question:
Does refresh rate matter here if I have max fps setting right below this?
you mean targetframerate?
The fps setting is just SetTargetFramerate()
Is refresh rate more of a native setting than that?
Either increment is always false, resolution count is less than one or current index is greater than resolution count.
targetframerate is a limiter, not sure they are connected in any way to display output but ill test
need to know for sure
Sounds good, i'm trying to whip up a settings menu this weekend for my Next Fest demo.
Valve people wanted to play it early
Right now the settings are basic but I could expand to allow refresh rate
yeah they are not tied
// See if current resolution has index
for(int i=0; i<resolutions.Count; i++) {
if(newResolution.ToString() == resolutions[i].ToString()) {
currentIndex = i;
break;
}
}
Ill just do this, theres no comparison for those structs built in
Maybe later on can do a dropdown or something but just need a working one for now
wont test, it just doesnt make sense, since your game can run at 1000 fps but will display only 60, so update loop and rendering are decoupled and
targetFramerate is update capper, while resolution is actual screen output cap
I'm setting uncapped fps to 666 just because
Who woulda thought the build had all these refresh rates
I'm adding UI content to be parented to my scroll view, and I'm seeing these red lines in the Unity Editor for some reason. What does it mean? Also it's not rendering my Panel UIs in the scrol view, but everything else
It means that the UI is inverted, either due to size or scale being negative.
your anchors are incorrect most likely
everything renders fine if I just instantiate as a child of the canvas. but making them the child of the scroll view cause this
er, causes the error in the screenshot above.
Good morning, any/everyone! So here's my current issue with my code. In the project, my error is, "Assets\ActivateGrabRay.cs(12,31): error CS0102: The type 'ActivateGrabRay' already contains a definition for 'rightDirectGrab' and 'leftDirectGrab' too". https://paste.ofcode.org/VjWANy7GEvy7RtnfxJmPyv
the issue is explained in the error
I am new, so I do not understand the error nor do I know what to do. Please enlighten me.
a class can't have two members with the same name.
therefore, you get an error: the type ActivateGrabRay already contains a definition for rightDirectGrab
already contains a definition for 'rightDirectGrab' and 'leftDirectGrab'
already contains
Soo, do I just change the class names then?
is rightDirectGrab a class name?
Hey so I have this triangle I used a procedural mesh for which fills in these moveable points. I want to fill in the triangle to go from r g and b with their respective location. Like this
I pasted a link to my code, y'all be able to see it, if that helps.
i saw it from the error, all the rest is me trying to help you understand what is wrong
public XRDirectInteractor rightDirectGrab;
This declares another field of type XRDirectInteractor
Both fields have the same name. This is illegal.
Now I understand.
So how do I fix it, just change one of the rights to something else?
and lefts
use unique names for variables within the same class
in the above case you can use the type name
public GameObject go_rightDirectGrab;
public XRDirectInteractor xr_rightDirectGrab;
Ahh, okay okay π haha.
In my mind, my brain said: "Now you're learning boyo! xD"
Testing rn: standby...
Results: Multiple Errors (ss provided)
well, yes, you changed the names of things
so now anywhere that used the old name needs to be changed to use the new name...
if I renamed public int foo; to public int bar;, every reference to foo would be broken
note that your IDE should be able to seamlessly rename variables. if your IDE is not set up properly (i.e. you aren't getting error highlighting and autocompletion suggestions in your code editor), you should really fix that now
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code*
β’ JetBrains Rider
β’ Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
I went to the first link website there, but how do I use it in Unity?
follow the instructions for whatever editor you're using
Will do
so I'm trying to get my project ready for vr but every project I've tried comes up with a null exception from the ParseArguements file I've tried everything I knew and dont know if im just a bozo i have the error and the code in the file.
`using System.Collections.Generic;
namespace Unity.PlasticSCM.Editor.ProjectDownloader
{
internal static class ParseArguments
{
internal static string CloudProject(Dictionary<string, string> args)
{
string data;
if (!args.TryGetValue(CLOUD_PROJECT, out data))
return null;
return data;
}
internal static string CloudOrganization(Dictionary<string, string> args)
{
string data;
if (!args.TryGetValue(CLOUD_ORGANIZATION, out data))
return null;
return GetOrganizationNameFromData(data);
}
internal static string ProjectPath(Dictionary<string, string> args)
{
string data;
if (!args.TryGetValue(CREATE_PROJECT, out data))
return null;
return data;
}
static string GetOrganizationNameFromData(string data)
{
// data is in format: 151d73c7-38cb-4eec-b11e-34764e707226-danipen-unity
int guidLenght = 36;
if (data.Length < guidLenght + 1)
return null;
return data.Substring(guidLenght + 1);
}
const string CLOUD_PROJECT = "-cloudProject";
const string CLOUD_ORGANIZATION = "-cloudOrganization";
const string CREATE_PROJECT = "-createProject";
}
}`
update or remove the Version Control package
man I'm sorry I found where it is but I don't know how to delete or update it. could you please tell me
thanks probably should of thought about that
When you instantiate a game object, how is the Instance ID determined? I ask because I am spawning enemies every X seconds and out of curiosity wanted to debug.log the instance ID's and noticed that 1 would be a positive number, and the rest (theoretically for as long as I would let the game run) were negative numbers.
the positive number is the actual prefab asset, instances in the scene will have negative instance ids
https://docs.unity3d.com/ScriptReference/Object.GetInstanceID.html
Hm. Interesting. I have to remember to check the docs first. I default to coming here for what end up being very easy to answer questions if I had just read the docs first.
they're often enlightening!
although it can be hard to know where to look, exactly
i guess i'd just google "unity instance id" in this case
your google results will vary with your search history, but I do get GetInstanceID as the second result
(on bing lol)
tfw we have a
emoji but no bing emoji
this is so sad
does anyone know a good tutorial for a menu thats short but useful?
Hoo boy, this was more of a challenge I wanted to do myself, was getting tight on time near the end.
I wanted to try to show how to setup something every game needs, a main menu, in as concise of a way as possible in a Unity Tutorial. I also tried to explain additional things like general UI advice in Unity, as well as Scene management (loadin...
tyvm
That one gets to the point pretty quick.
nice
well, only if it works, right?
its good
if it works
ig
alr
pretty much to the point
good
Yep. Then it's basically rinse and repeat. I use that method for slapping stuff together just to get a MVP together.
i have a question for you programmers
what is the easiest way to find people to make a game inspired in another game that people barely remember of? (Little Big Planet is the game im talking about)
!collab
We do not accept job or collab posts on discord.
Please use the forums:
β’ Commercial Job Seeking
β’ Commercial Job Offering
β’ Non Commercial Collaboration
i dont think anyone wants to collab on a "Fan Game" of a game that got shut down by sony
or well, a franchise of games
i alredy have a post there
way to find people to make a game
that's literally what collaborating is.
so if that works thats that
i know about that
but if that doesnt work i mean
well if the resources the bot linked don't work out for you then you can try and find people elsewhere π€·ββοΈ
btw how did u make that text on the top row?
nvm
Like this?
yes
I'm making a game where if you interact with a sink, it makes the object you're holding wet. Is there a specific line of code I could use that could make the object watery/reflective?
probably shader, use shadergraph or find premade one
It... depends on your application. Each cell should have a reference to the same object... if you want it to. But then you're saying they should all be unique. I'm not clear on your intended outcome, nor what you currently have in place
I'm not sure if that does anything at all
What does Get return?
Probably doesn't matter what it returns. Unless maybe the returned object overrides the assignment operator.
But what are you calling "a reference" here?
basically it creates a local variable referencing whatever you Get(). Then you assign the value to that variable. When the execution goes out of scope the local variable is destroyed.
This is the same as your code:
var reference = Get(a, b);
reference = value;
The original element that you get or the collection that holds it are not affected in the process.
Tangent: can you actually "return a pointer" in C#? I know I could do it in the C world, then assign a new value to the deferenced pointer - but I haven't seen that in C# as of yet
Before even tackling your issue, your code is invalid. It doesn't do anything...
You can do that in an unsafe context, but it's kind of a violation of the C# principles.
Good to know. Maybe even preferable - thank you :)
Is that not the actual code that you're using?
When asking for help, please provide the actual code, because some context might be lost otherwise...
They're probably gonna say the same.
*Going to have a look in the C# discordπ
I'd like to follow along as well... I need uh.... !csharp
!cs
bah
They probably refer to https://discord.gg/csharp
Thank you π. I know there's a command to get that invite, but I clearly fumbled
This is totally different to what you shared though
Sure... my confusion was assigning a value to a value returned from a method call though
interesting
it returns a ref okay.
in C# by "reference" we imply an instance of a class. The ref keyword is indeed similar to C++ references.
So, if you want to clone the object, you need to construct a new instance and copy all the fields from the original instance.
If you're dealing with unity Objects there's the Instantiate method, that basically clones the instance.
Then you'll need to construct a new instance manually with new YourValueClass(params)
If there's polymorphism or interfaces involved, you could define a Clone method on the base class/interface and implement it in each of the subclasses.
Yeah, like a copy constructor.
There are many ways to go about it. It shouldn't be too different to cloning heap objects in C++.
Umm... What's Array2D.Fill() and Get again?
Yes. It does that.
You'll need to loop the array and assign a new Wall() to each element if you want them to be unique.
Probably. I don't think you should be thinking about performance at this stage...
Then maybe use structs? It kinda feels like you're diving head-deep into something complicated without understanding C# properly. You can't apply the same logic as C++. Gotta understand that.
C# and unity can be as performant as C++. If you do your learning properly.
If an item is given, it should not be added to the inventory and the ammunition county should increase. How to solve this?
hey im trying to make a bullet shoot and hit the player to take damage and then delete itself, it isnt deleting itself and it isnt doing damage either
using UnityEngine;
public class EnemyBullet : MonoBehaviour
{
public int damageAmount;
public float bulletSpeed = 5f;
public Rigidbody2D theRB;
private Vector3 direction;
// Start is called before the first frame update
void Start()
{
direction = PlayerController.instance.transform.position - transform.position;
direction.Normalize();
direction *= bulletSpeed;
}
// Update is called once per frame
void Update()
{
theRB.velocity = direction * bulletSpeed;
}
private void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Player")
{
PlayerController.instance.TakeDamage(damageAmount);
Destroy(gameObject);
}
}
}
It depends on the use case. There are situations where a reference would be more performant.
{
[SerializeField] private AmmoClipItem ammoItem;
[SerializeField] private Rigidbody _rigidbody;
[SerializeField] private PickUpSnd pickSnd; // access to the pick up sound class
[SerializeField] private GameObject outline;
private readonly float _impulseStrength = 200f;
public Item Item { get => ammoItem; set {} }
public PickUpSnd PickSnd
{
get => pickSnd;
set => pickSnd = value;
}
public GameObject Outline
{
get => outline;
set => outline = value;
}
private void OnEnable()
{
gameObject.name = ammoItem.Name;
}
#region Server
[Command(requiresAuthority = false)]
public void CmdInteract(GameObject playerObject)
{
var isSuccess = PickupItem(playerObject);
_rigidbody.AddForce(Vector3.up * _impulseStrength);
RpcInteract(playerObject, isSuccess);
}
private bool PickupItem(GameObject playerObject)
{
var armorManager = playerObject.GetComponent<ArmorManager>();
if (armorManager.IsNoSpaceForAdditionalAmmo(ammoItem.ammoType, ammoItem.AmmoCount)) return false;
armorManager.GiveSomeAmmo(ammoItem.ammoType, ammoItem.AmmoCount);
Destroy(gameObject);
return true;
}
#endregion
#region Client
[ClientRpc]
public void RpcInteract(GameObject playerObject, bool isSuccess)
{
if (!isSuccess) return;
PickSnd.PlayPickUp();
Destroy(gameObject);
}
#endregion
}```
depends
a giant chunk of memory you have to copy all the time vs a null test or ref compared
whats that pattern called flyweight?
also AOS/SOA
π
Should I kill the Unity task, delete the library and re-open? The issue originally was that Visual Studio package was giving errors after I upgraded to 2.0.18
2.44GB
yeah nuke library
also .vs and temp for good measure
and the csproj and sln
Is there a size threshold that I should look out for going forward?
im just comparing to my experience with 200+gb projects that took sometimes 2 days to rebuild lib cuz of some corrupted assets
what i mean is that you dont need to keep state of each cell in the cell
you can share same cell data class reference and use ref comparison and allocate closely the cell data, swapping with new instances only on persistent changes
Ohh the folder
"show hidden files" if you dont already
Yeah I see it
yeah even with ref you are bumping into struct length
will it fit into a cache line? how many reads you will need to read the whole thing?
yes and can you guarantee it?
with object references you can share a single instance over many cells
it will remain in cache
its pretty much the same exact thing
class array in c# is the same as ref/ptr array in c++
same problems
cache lines, copy semantics
SOA is great also the read lines from each array will remain in cache, but you can layer grid properties
i.e. at any point you append another array with some primitive type
to express some new cell property
If it was easier, you probably didn't really do that much for performance in it anyway.
So no point being picky about it in C# either
i feel like my point is not being cached
Then implement it.π€·ββοΈ
You just saved me countless hours of headache. Thank you.
Also the manifest file solution. Can't believe it was that easy
rule of thumb for the future if it takes more than 30 mins without going into "asset x, asset y..." nuke it
probably even shorter just hard to tell since project size matters
but id guess anything below 10 gigs is a safe bet if its around 5-10 minutes
also there are scenarios where you simply cant find the corrupted asset
there are thousands of them and 1 is broken and break import
its important to organize project, and dont keep redundant "maybe will use later" assets in the project
Agreed. This is sort of a throwaway prototype so I've not been as vigilant as I normally would be. Just frustrating as hell how many projects I've had to nearly abandon because of the engine itself going haywire.
Back in business for now though, so thanks again!
99.99% of cases you can fix
You need to explicitly define constraints for T in your method
You're probably confusing generics with C++ templates. They're not the same...
If you want to keep on developing with unity and C# you'll need to learn it properly...
Hey guys, I have a small problem here.
So at some point in my code I start a coroutine, and this coroutine has a line that looks like this "yield return new WaitForSeconds(seconds);". So the coroutine waits that amount of seconds before running the code that comes after.
But I also make a check in Update() and if the condition is meet then I try to stop the coroutine with StopCoroutine("CoroutineName"); because I don't want the code that comes after that yield to run anymore.
Though, for some reason, the coroutine does not stop, even though the condition is meet (and, the rest of the code in the coroutine gets executed).
I would really like to know what I'm doing wrong.
assign StartCoroutine to a Coroutine variable
then stop that
eg
Coroutine myCoroutine;
void TheMethod(){
myCoroutine = StartCoroutine(MyRoutine());}
void Update(){
if(stuff)
StopCoroutine(myCoroutine);
}```
public GameObject cubes;
public static void Use (string itemName) {
if (itemName == "wow1") {
cubes.SetActive(true);
i get error that cubes isnt static its public but im trying to refernce it
in a static thing
anything in static class needs to be static
and you can't assign it in the inspector if it's static
Oh, that works!
Is that the general way of doing it? Looks a bit strange to me.
Yeah it's usually how it's done
cud i reference the object in scene then like
StorefrontDemoScene.Main.wowEnabled.SetActive(true);
Oh, I see. Thank you very much!
why is this class static in the first place ?
just make the instance of it static
so you can access public methods/whatever else public, directly through that instance
uh
public static GameObject cubes;
like that?
if i do that
i cant drag it
to inspector
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Runtime.InteropServices;
using UnityEngine.SceneManagement;
public class UseItem : MonoBehaviour {
public GameObject cubes;
public static void Use (string itemName) {
//Debug.Log ("Custom item usage executing for item: " + itemName);
if (itemName == "wow1") {
cubes.SetActive(true);
its in public class
is there a reason you don't just make this UseItem class referenced in another script instead of doing anything static ?
like [SerializeField] private UseItem useItem; or public UseItem useItem
then just drag the script in
access it this way
uh
i get errors if i dont have that part static
cuz it came with a bunch of other like scripts n stuff
uh i can do
GameObject.Find("wowEnabled").SetActive(true);
but the problem is it cant find it cuz its not enabled
hm
it can disable it tho
i use playmaker for scripts
so i enable them then have the playmaker do stuff
you use playmaker, why are you in a #archived-code-general
this should go in #π»βcode-beginner at very least then
you seem to misunderstand some fundamental c# concepts
what is a way to use inspector to filter "types" of components i want to find from physics colliders
i want to collect a list of all objects that have a component that i want to decide from a list of types
not sure how i would set that up though
i cant use layers either
I have an player appearing animation, which should be played on start. But I think it's playing even before the scene is loaded and I am not able to see it. Is there any way to delay it?
yes, with Coroutine, for example
You need to have a list of components with Colliders in your script?
I see
so you just need to find GameObjects and then use .Select of LINQ I guess
GameObject[] allGameObjects = FindObjectsOfType<GameObject>(includeInactive: true);
// for example
GameObject[] withRigidbody = allGameObjects
.Where(w => w.GetComponent<Rigidbody>() != null).ToArray();
If you're doing that why not just use FindObjectsOfType<Rigidbody> in the first place?
I know that, I have just shown the way to find something else for him
ofc you can do smth like that too:
Rigidbody[] rigidbodies = FindObjectsOfType<Rigidbody>(includeInactive: true);
My current approach is a class with an enum
So I can bit flag to get all objects with the signature but it's annoying having add enums for new components
how about
List<Type> types;
List<Component> selected;
Component[] components = FindObjectsOfType<Component>
foreach (Component c in components) {
if (types.Contains(c.GetType()) selected.Add(c);
}
I would like to get some more help on this one if possible, i updaetd the code and will now post a vid
https://gyazo.com/c2f06c6a29ecbb839c1d46257543ab61 π
what is the issue?
is it player?
how do you control them?
Well i'm not sure it's a character controller btw, and it just does this, i can;t go further then that radius and when i let go of the contruls/buttons it moves to the top middle position :/
full 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.
In unity list type when serialised only let's me place game objects
Into the list
then make a wrapper for it
Type is, iirc not serializable by default
you can use nameof and Type.GetType to convert between strings and actual Types
how would i check an area for the highest y point in there optimally? assuming you can do this by just raycasting from above everywhere
what do you mean?
imagine you have a black and white heightmap and you want to get the whitest point. i'm not working with them just making an analogy.
you can use Bounds class ??
it's collider based? the area can have multiple objects
it can be collider based too, collider does have Bounds Component
i mean it cant be collider based
anyway i think i'm overcomplicating it
i just need to do a step down function. teleporting the player down on steps
@rotund burrow
Collider collider = GetComponent<Collider>();
Vector3 maxPoint = collider.bounds.max;
so the idea was to check if player is in air and its y velocity is around 0, then check if the distance to the ground is short then you can tp there
see Bounds struct https://docs.unity3d.com/ScriptReference/Bounds.html
// smth like this ??
if (isGrounded && Mathf.Abs(rigidbody.velocity) <= 0.2f &&
Vector3.Distance(transform.position, grond.transform.position) <= 0.2f)
{
// tp there
transform.position = grond.transform.position
}
yeah i know how to code it the problem is the ground isnt flat
what? English, please
How do I make it so a recursion function breaks out if it has run x amount of times?
someInt += 1;
I am glad then
check the distance, yes
what distance?
you need to check the distance between the player and the ground I guess
according to our previous conversation
ok ??
i dont get you
what's rendered vs what's shown. there's a lot of extra renderering done that's just hidden. is there a way for the camera to only render a certain portion of the screen? similar to blenders "render region" function
That would be wasteful. To do it efficiently you would adjust the camera settings to give you the desired region.
?
that's what i'm trying to do
The current rendering is wastful, it's rendering regions that aren't being shown, i'd like to render only was visable
I donβt understand, just change the fov or focal length
it's a portal effect, i have two cameras, one main camera and one rendering the view through the portal. the main camera is on the left, the portal camera is on the right. the portal camera needs the same FOV as the main camera otherwise the portal effect is ruined
okay let's try again. Player is going downstairs i want to teleport it on the next step instead of it falling there. The problem is checking the distance between player and next step. You cant just do one raycast down, because there might be holes in the ground or the step after next step (which is lower and that will teleport you inside of the stairs). IDBB you cant check distance between transforms, let's say all of the ground is one object.
the red regions are being rendered when they don't need to be rendered
the areas shaded in red are never shown and so are a waste of time being rendered
for one portal it's not that bad but when you have a few it tanks performance
you'd better pin me first
please, show your stairs, cause I don't really get why you cannot use Raycast
it's like the image above
show inspector, please
and also say, where should player be teleported here?
then you should spawn Raycasts from Bounds 4 bottom borders
and spawn player on the hitInfo's position
okay i think this discussion just isnt worth it. I'm gonna do a raycast check from behind the player. meaning the point of the collider where -velocity hits it. it's not a general solution but will work for now
it will work with the solution I have provided above
or if that's too hard, you can decrease player's position until they are grounded
i have a cylinder so you would have to do like 9 raycasts and then compare the distance of each one
then decrease player's position until they are grounded
right i can just... push the player down
it would be similar to teleporting
just a fast push, funny how i didnt think about it
rigidbody.AddForce(Vector3.down * pushForce, ForceMode.Impulse);
yeah i know how to code. thanks for your idea but you're being condescending.
what is this supposed to mean now? I was just trying to help you
Does anyone have a resource for getting repeating textures for things like distortion/noise maps?
nevermind i'm just cynical. thanks for your help
Usually I'd either generate it in the shader (Gradient Noise node, Voronoi node) or pre-generate it in a texture in Photoshop/GIMP/etc
Offsetting a UV coordinate with noise will produce some nice distortion too
SphereCast π Works well with capsule colliders
Or CapsuleCast but usually SphereCast is enough
Don't have to worry about holes smaller than your capsule because the sphere won't fit through
If the door is a render texture the portal cam renders to, then it will only render whatever that doorframe covers
that's what i'm trying to do but it renders the whole scene
the portal camera renders to a render texture, that render texture is then mapped onto the door. the things that the doorframe covers are still rendered just obscured
why is MonoBehaviour undefined and what can i do about it?
Follow the !ide configuration steps
If your IDE is not autocompleting code
or underlining errors, please configure it:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code*
β’ JetBrains Rider
β’ Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
Why is the ObjectList empty, then i return it, but the lists i join are not empty, Code:
public WaveObjectData[] GetObjects()
{
List<WaveObjectData> objectList = new List<WaveObjectData>();
for (int i = 0; i < tileTypes.Length; i++)
{
objectList.Union(tileTypes[i].objectDataList).ToList();
}
return objectList.ToArray();
}
Looks like Union returns a new list as a result. You are not doing anything with the return value
Maybe you want objectList = objectList.Union(...).ToList();
ahh, so it should say objectList = objectList.Union(tileTypes[i].objectDataList).ToList();?'
Yepp
okay, thanks, ill try it
does anyone know, how to check when user is holding the mouse button while over the GUIElement or Collidion in script?
// this code works just when button is pressed (the target is destroyed then)
// I need it to be destroyed, when the button is held too
private void OnMouseDown()
{
if (CompareTag("GoodTarget"))
{
Instantiate(explosionParticle, transform.position, explosionParticle.transform.rotation);
scoreManager.ChangeScore(1);
Destroy(gameObject);
}
else spawnManager.GameOver();
}
Btw, objectList.AddRange(tileTypes[i].objectDataList); could work too, and probably more performant π€
Oh wait does Union check for unique values
If thats the case and its needed then nvm
yes, that works too, thanks for the tip
don't think i need it so, give me the same result
Yeah ok go with AddRange
is it better than raycast from to the mouse position?
Hey good day.
Today i present you a question with some math content (so i need help xd).
I want to get from a list of n elements at least 1 element at random an n elements at maximum and i dont want to have the same probability for each of the elements to be selected.
Any ideas?
I think thats pretty much what EventSystem does
Honestly, I haven't ever checked if Raycast works on UI elements, so dunno.
Depends on the raycast, there's even EventSystem.RaycastAll
https://docs.unity3d.com/2019.1/Documentation/ScriptReference/EventSystems.EventSystem.RaycastAll.html
there's a separate graphic raycaster component
ok, so I have this. Now I need to check UI's tag and destroy it if it's tag is "GoodTarget"
private void Update()
{
if (Input.GetMouseButton(0))
{
if (EventSystem.current.IsPointerOverGameObject())
{
Debug.Log("Clicked on the UI");
}
}
}
How do I get information of that UI
Which part? Checking tag or destroying?
tfw no MeshCast
Literally unplayable
private void Update()
{
if (Input.GetMouseButton(0))
{
if (EventSystem.current.IsPointerOverGameObject())
{
// if it's tag is "GoodTarget" => Destoy(thatGameObject);
}
}
}
Also, why not use the pointer callback instead of polling in Update?
We have it for convex meshes at least!
https://docs.unity3d.com/ScriptReference/Rigidbody.SweepTest.html
nice
there is nothing else to tell you, make the desired framing fit the texture, then nothing else will be rendered. if you mask the texture, obviously you produce waste.
what do you mean?
oh, yeah
You'd be able to evaluate which mouse button was pressed as well: https://docs.unity3d.com/2019.1/Documentation/ScriptReference/EventSystems.PointerEventData.html
Hi im triying to make a 2d game with top down view and I'm trying to get my player to get in and out of the car,does anyone know how to do it?
@dusk apex should I use it in the script that's attached to the target, right?
you do not understand a word i am saying
Even AAA games can't get "getting in and out of cars" right lol
On whatever's responding to being clicked
yeah, thank you
clang
I would say to start with a simple teleport: you hit a button, and now you're in the car
then, you can figure out how to make the player just...lerp into the car
and then maybe throw in sound and animations for a door opening
Yep, make it work first. Then make it look smoooth @brave radish
Make sure to thoroughly read the description, to avoid potential minor inconveniences @gray mural
Yeah im triying to make it simple but when I press the key assigned to in the car and colliding with it, it doesnt works
I'm trying to see if my player is colliding with any of the colliders that are children of one gameobject. From everything I've seen online this should work, and the "s" that separates the two similar methods is clearly there. However, this is still acting like GetComponent (singular) and is only giving me the collider of the first child among them. How do I get them all?
Show your code and object setup
my vs is constantly getting stuck on errors that don't exist. is there a way to stop this from happening? restarting the IDE every 10 minutes is infuriating
So I'm having an issue, but its across 4 different scripts, should I just share them all on separate paste sites?
Yeah put the scripts in separate links
okay
Ok so for this to work, you would have to press down space on the exact physics frame that you enter the collision
you also need to configure IDE
I would use a trigger collider, detect the availability in OnTriggerEnter2D/Exit2D, check the input in Update and do the action only if something is available
Or use collisions but change GetKeyDown to GetKey... But having to touch the car isn't the best for game feel
So, I'm trying my hand at a wave function collapse, and it works great when using the object list in this script: https://gdl.space/tamawuduwa.cs, but I wanted to change over to a TileType system, to cut down the setup time, so I don't have to set up each rotation for each tile, and also store them as Scriptable objects, but now it is not working with my new system, then I check it in the foreach loop in script above. Here are the other ones: TileType: https://gdl.space/evahocikab.cs, WaveObjectData: https://gdl.space/yahonoyuwe.cs. Can anybody help me, i know it's quite a lot, but I'm really stuck.
BTW the CreateOtherTiles() is run in an editor script using a button in the inspector.
what does "it is not working" mean?
it means that the tiles that should be the same are not the same and my generation scripts cant use them, i check for this on line 24 in this script: https://gdl.space/tamawuduwa.cs
by default, comparison is done by checking for reference equality
you only get true if the two things are literally the same object
okay, sΓ₯ not of the values of the things are the same?
is there a way to tell 2 different scriptable objects apart?
for instance
one is a consumable and one is a armour object
i'm a little unclear what's going on here: you're making a list of WaveObjectData, then adding lists of WaveObjectData data from various places to it
then you're checking if every element in that list is also in objects?
well, if they have different types, then they won't be compatible in the first place
i'm guessing they have the same type
how would I display the points that I got on one scene to another scene. Like how would I make the points I got go to the death scene
both derive from 1 base scriptable object class π
1: do not cross post
2: did you read my answer?
oh sorry didnt know you were talking to me
yes, each TileType has a list of WaveObjectData, that is the different orientation of that Tile, Then then get added together in one big list, that holds them all, that is then referenced with my old system of just making all the WaveObjectData by hand. The old method works, but the new doens't and i don't see what the difference is
it'll be because objects has different instances than objectList
even if the data is the same
they are two unrelated objects
so, you'll need to implement your own Equals method if you want to test for equality properly
in inventory all item types are compatible but i need a way to check if the on i click on is a armour SO
you can always use the is operator
i do that for my own game which also has an inventory system w/ multiple derived types :p
okay, but i still don't see what the difference would be from my generation script, that just call the GetObjects() method, to get the list, and with the old objects is works, but with the new objectList it doesn't
it feels weird to do that -- it usually indicates you're doing OOP wrong
and why do you think it doesn't work?
strictly because the elements of objects aren't contained in objectList?
because it doesn't generate the world with the objectList, but it does with the objects, and i thought if i checked if they were the same, which they should, then i might come closer to the issue
you can only check if they're the same if you implement a meaningful Equals method
!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.
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(BoxCollider2D))]
public class clickable : MonoBehaviour
{
void OnMouseEnter()
{
if (gameObject.tag == "inventory")
{Debug.Log("Add to inventory");
mousecontrollerscript.instance.Pickup();}
else if(gameObject.tag == "viewable")
{
mousecontrollerscript.instance.View();
Debug.Log("view");
}
else
{
mousecontrollerscript.instance.Default();
}
}
void OnMouseExit()
{
mousecontrollerscript.instance.Default();
}
}
(I feel like this is a very verbose way to get the cursor to change on entering certain objects. any easier ways?)
simplify until you can find the problem
knock it down to one kind of tile
i didnt know there was an is operator tbf ty β€οΈ
not too sure how i would match it against ArmourItem tho ngl
if(nearest_slot is ArmourItem) {
// do code
}
be like this?
or this
if(nearest_slot.GetItem() is ArmourItem kk) {
// do code
}
i think the second one makes more sense actually
ill test it out with a debug.log
i mean, that depends entirely on how your classes work
what is the type of nearest_slot?
your IDE would probably complain about it always being false
Yeah came up with a yellow warning
ill try this for now
ill see what output i get
the result of nearest_slot.GetItem() will be assigned to kk if the cast works
ahh i see
thats pretty handy
is working fine π
also, i dont know if my system is practical. i have a script called ArmourIdentifier that sits on the armour slot and you can set it to what the armour slot is for instance if its a helmet in the inspector you can set it, then i reference that script and check it against the SO
Okay so i found an issue, in this script, the FourSides doesn't rotate the sides correctly, https://gdl.space/evahocikab.cs, here is a picture of the outputs: is should have rotated it so it is north and west that are road, but it doesn't
i had a lot of fun implementing this exact thing in an ECS game..
lots of ways to screw up the rotation, specifically
Okay, but I really don't see the issue, it look all fine to me...
to compare 2 enums do you need to cast them to a int?
that was roughly my experience, haha
i was writing code to figure out how to rotate two tiles to make certain faces touch
it was very messy
no, they'll implicitly convert to ints
yeah, I renamed a variable and then it worked, no idea why
i'm guessing you want equality checking?
i first went through the authoring data -> runtime data conversion, then did a ton of work in a bursted job
so it was a nuisance to reason about
hey, can someone please review this?
tried to do it that way but my editor was screaming at me so i had to cast them to ints
show your code.
it's fine for me if I compare two enums
e.g. EnumType.A < EnumTypeB or EnumType.A == EnumType.B
not so much if one is an int
again, show your code.
Hi! I am using position handles to move the target position (a Vector3) of an IK system, but apparently when I use the handles the new position is not serialized. Like if I change the position and then I enter in play mode, the change is there. But when I exit from play mode, the position is reverted back to the previous one
This is the code of the position handle:
#if UNITY_EDITOR
[UnityEditor.CustomEditor(typeof(FabrikSolverAuthoring))]
public class CustomEditor : Editor
{
public void OnSceneGUI()
{
var authoring = target as FabrikSolverAuthoring;
authoring.Target = Handles.PositionHandle(authoring.Target + authoring.GlobalOffset, Quaternion.identity) - authoring.GlobalOffset;
}
}
#endif
It basically makes position handles useless since what I do is reverted back after 1 play
you need to wrap that in a change check
you should mimic what the example code does
Oh thanks, I'll try!
i'm guessing that, if you don't do this, unity never notices that you made a change
thus the behavior
And if I have 2 handles in the same script (for 2 different variables)? I do a EditorGUI.EndChangeCheck for both of them?
i dunno about that -- i guess i'd just put both in the same change check
It works, thanks β€οΈ
Does anyone know how to create nice mouse effect, when dragging the left button?
I mean drawing with mouse actually
that's like additional effect
when mouse is moving, it should have like tail (I guess)
ok, thank you
LineRenderer will do it as well
how to I "name" those type of methods?
volumeScrollbar.onValueChanged.AddListener(_ =>
{
// do smth
});
like "delegates" or "listeners"?
you dont, they are lambda expressions, they not have a name
delegate ??
no, lambda if you need one
ok, thank you
Hi,
I'm currently working on a tilemap based game in unity and tried to create a custom RuleTile.
In this I override the RuleMatch function like this:
public override bool RuleMatch(int neighbor, TileBase tile)
{
switch (neighbor)
{
case Neighbor.This: return CheckThis(tile);
case Neighbor.NotThis: return CheckNotThis(tile);
case Neighbor.LowerLevel: return CheckLowerLevel(tile);
}
return base.RuleMatch(neighbor, tile);
}
Is there any way to get information about the (relative) position of that neighbor that is being checked in regards to the tile with that script on it?
transform.parent.DORotate(startingRot, 0.2f, RotateMode.FastBeyond360); how do you do a full 360 revolution tween on a single axis with dotween? since the start and end rotation will be the same
{
GameObject obstacle = Instantiate(prefab, transform.position, Quaternion.identity);
obstacle.transform.postion += Vector3.up * Random.Range(minHeight, maxHeight);
}```
`Assets\spawnObstacles.cs(25,28): error CS1061: 'Transform' does not contain a definition for 'postion' and no accessible extension method 'postion' accepting a first argument of type 'Transform' could be found (are you missing a using directive or an assembly reference?)`
Why does it say transform doesn't habe position
which line is the error coming from?
oh
postion
that is not how you spell "position"
i mostly just use autocompletion
for some reason i dont get autocompletion on visual studio
If your IDE is not autocompleting code
or underlining errors, please configure it:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code*
β’ JetBrains Rider
β’ Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
it will make your life much easier
follow the instructions from top to bottom, to make sure that everything is set up correctly
although, before you start, try clicking "Miscellaneous Files" in the top left
if that has no other options, then go ahead and do the steps
but it's possible it's all set up properly already, and that you just don't have the project selected
I will
thank you so much
is there a big difference between using visual studio code and visual studio for unity?
is this where is ask whats wrong with my code?
for (int i = 0; i < SMR.materials.Length; i++)
{
SMR.materials[i] = PhaseMat;
Debug.LogError("assogner mat " + SMR, SMR.gameObject);
}
This code does not change the material SMR.materials[i] properly to PhaseMat... any idea why?
do you have any other code that could be assigning to the material slots?
Pretty much, but make sure to read the #854851968446365696 so you know how to ask a good question!
nope... the only other instance i edit these materials, is when i assign a different main texture to display a player has been damaged.
!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.
Well, completely ignored the instructions in the read-me altogether
._."
zoop
https://gdl.space/lapokigeto.cs
I'm trying to make it such that when I press Boost, and only Boost once, will cause the character to hop (ie. If I tapped Melee and Shooting, the mech should not hop, and double tapping or holding it down will cause it to not hop as well)
but currently while i got the latter done, regardless of combination I did the chara will always hop as long as the boost button was pressed
please
Please post !code correctly
π 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.
my bad
I have a problem where my raycast2d is too inconsistent, can someone help pls
https://paste.ofcode.org/HKuuCVhSmRWQ9jCZ3RbCsd
Not sure if this is the cause, but the direction you pass as argument 2 to Raycast should be normalized. That way its length doesn't depend on the distance between the two objects
Also, your GetComponent in your if statements are not needed, as .collider is already a Collider2D
help pls?
I fixed, it still cant see player when he is moving around the enemy
In FixedUpdate, all of your new WaitForSeconds don't do anything here. You need to be in a coroutine and you need to yield return them in order to have an actual wait happening
Here all your code executes at once
do I just make the FixedUpdate start a coroutine with the coroutine store everything else in that case?
(so that's why yield return new causes the visual studio error to ring)
I'd make a coroutine with an infinite loop in it, and start it once, in Awake or Start
alright
And for the error, yielding can only be done in a coroutine so that's probably why
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code*
β’ JetBrains Rider
β’ Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
You need to debug a bit, log whether your raycast detects anything, and if it does, logs the name of the object it detected
With that set up, make sure you get the right object detected
hey im getting this error:
Gradle failed to fetch dependencies.
what do i have to do get rid of this error
Mobile? Ask in #π±βmobile
no trying to resolve in unity error
and it's not an error with your code. it's an error trying to build for #π±βmobile
but im not trying to build it to my phone, so how does it have to do with mobile? sorry ive been using unity for 3 weeks now im a bit new
I fixed it, thanks
does this error happen when you try building the project?
no, it happens when i try to resolve the project
building to my phone doesn't have any problems
wtf does "resolve the project" mean
Unity doesn't work with Gradle does it? Or latest versions do but I doubt that since it's for Java stuff
afaik the only thing unity uses gradle for is building for android
assets -> external dependency manager -> android resolver -> resolve
would you look at that, it is an issue you should be asking #π±βmobile about
No, we're C# devs
The android pros in the channel you've been linked to a few times do, though
This should not be going down at all, Does anyone see whats wrong here:
https://paste.myst.rs/credpi86
are you repeatedly hitting reroll here?
we'd probably have to see that singleton, but i'd imagine objects are probably being dequeued from the generatedUpgrades queue
added, but now it got worse
it now doesn't register Sub1/Sub2/Sub3 at all
Yea, each time I press Reroll, the func with the Debug.LogError is ran
the UpgradesManager?
yeah, we'd probably also need to see anywhere else that the queue is accessed
https://paste.myst.rs/6pgcz26t this is the upgrades maanger
a powerful website for storing and sharing text and code snippets. completely free and open source.
Why is MonoBehaviour not defined and what can I do about it? I already double checked the IDE setup and nothing seems to be wrong.
wdym by "not defined"? are you referring to the lack of syntax highlighting for it? because that would mean your IDE is not fully configured
its also not autofilling unity syntax like Input.GetKeyDown
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
if you have actually gone through everything in the guide then regenerate project files and restart visual studio
Looks like that since the original amount of upgrades is not a multiple of 3, it dequeues too much when you have less than 3 of them. Your for loop at the top should probably not have 3 as the upper bound, but the max between 3 and [upgrade list count]
still doesnt work
the UsableUpgrades list should not be shrinking
that's the issue
since I add the previous ones back to it if you reroll
show that you've installed the unity workload and set your external preferences correctly
k 1 sec
are you certain that you aren't calling Dequeue or Clear on the queue anywhere else?
i would specifically check if generatedUpgrades contains what you think it does at the start of the reroll function
I am using Dequeue in various places
Not too savvy with Queues tbh, not Often I use them
When you use Dequeue it removes the first object in the queue so if you don't put it back then suddenly your queue has fewer objects in it
I use Dequeue on the first generation. then when reroll is pressed, I dequeue it too
oh. perhaps I should have a list along side the queue then?
to add them back if rerolling
@somber nacelle
yeah i didn't need you to ping me again.
mb
regenerate project files there and double click a script in unity to open it
prove it. do it again now and screenshot what the entire IDE looks like with the solution explorer in it open
Show VS open with a script in view. As well as the solution explorer on the right
the solution explorer is the project tab right
No in VS
no, it's a tab inside of Visual Studio that is literally called Solution Explorer
ok
View > Solution Explorer if it's closed
do you happen to have more than one version of VS2022 installed?
wdym that one version
Nah VS is just freaking out here
Where it says Incompatible on the right, right click that and select Reload With Depedencies
Hello, I have a problem, with this code this is not true that all the cubes should be red in my scene?(i have some tiles in my scene).
well, if none of the nodes are walkable, they'll all be red..
walkable: (line 62)
are you doing something strange like creating a new instance of something on each reroll? your code looks fine from what you've shown, but perhaps you can verify in OnRerollPressed the state of generatedUpgrades - it's behaving as if it's not adding anything back to the UpgradeManager
yes but this is my scene and idk why
that doesn't tell me very much
is this a 2D game?
you're using a 3D physics query there
it's the Queue Shenangians. now I populate a list when I enqueue upgrades. then if I reroll I just add the list range back to UsableUpgrades then clear the list. Works like a charm
yes
ezpz
use Physics2D methods.
whats the problem here?
well, you tried to use await in a non-async method...
hmm.. what's queue used for at all then?
you read the error, right?
yes but I dont wanna make the method async
Then you cannot use await
Don't use await
Then you can't use await in it
Honestly I can't remember, made this over a year ago, it's quite complex to give an answer straight away π
https://paste.myst.rs/ksbrrtqj but feel free to give it a looksie
so how do I await for the task to finish then?
Google. This isn't unity specific
Maybe there's a .GetValue() that's synchronous
There's a whole lot of info out there on how to use await.
but im lost

like how do I turn from an bunch of async stuff into finally waiting for the async stuff to end
pretty sure you can just start the task and then check if it's done in a coroutine
importantly, you can't run it on another thread and have code immediately run on completion
since only the main thread is allowed to mess with the game's state
looks like it's probably firebase which actually has a ContinueWithOnMainThread extension method
well that's nice!
so you want your entire game to freeze
yes
i'll implement a loading screen and stuff later
but for now I just want to do some quick dirty stuff
do I just while (!task.IsCompleted);
xd
i mean is there not a non-async overload for GetValue?
doesnt seem to be nope
tbh, I'd suggest putting that in your code and seeing what happens - might be an important step in understanding what's going on
pretty sure if I do that the game actually counts as frozen because it doesnt yield
well, it's always gonna "count as frozen"
the only question is whether it unfreezes at some point
Thanks, I was following a video for my code and didn't know that.
this assumes you are using 2D colliders, of course
yes but the OS will say its frozen and attempt to close it
you could very well be using 3D colliders in a 2D game
after a period of time
this is why non-blocking logic is very important...
ok i'll just implement the loading screen 
yes, but in this case I want the main thread to pause
you said you want that to happen though?
you asked how to set off a grenade and now you're surprised that there's a giant hole in the wall π
if you join a thread, you block until that thread finishes
so, the exact same thing happens
there is no wiggle room here
if you block the main thread, the game freezes
the difference is the while(true); uglyness
that's basically what a WaitForCompletion method would do
and it's also exactly what .join() would be in Java
just sit there until it's done
will unity allow you to sleep the main thread?
while() doesnt yield tho
i just use await task.delay() and hope it will give up the cpu
the exact same thing happens if you join a thread in Java
There also appears to be a Task.RunSynchronously(), which seems to be a fancier way of blocking
thats all I wanted yes
i dont if there is conditional signal in c#

it doesn't matter how you make the main thread wait
a busy loop or sleeping or whatever
the game will freeze
you blocked the main thread.
you only have two options:
- block until the data is available
- don't block and deal with the data not being available yet
oh wait, if you only need to do one task and the main thread must wait for it finish, why dont you put it on main thread?
what type does that function return?
actually, I'm specifically interested in the result of Child()
https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmlreader.getvalueasync?view=net-8.0
this one?
what type is that thing returning?
no, firebase rt database get
can you point me to the documentation for the type returned by Child?
i guess that's right
and GetValueAsync is returning a C# Task
wasn't sure if it was something ~special~
but yes its just a C# task
do exceptions not get printed when im on a different thread?
float randommod = Random.Range(90, 111) / 100;```
random mod sometimes returns 0, how?
because im starting to lose my mind over code not working
(infact almost always returns 0)
try Random.Range(90f,111f)
you are using the int version of random.range
i do remember something like that happening
maybe
if you aren't actually awaiting your tasks and you aren't handling exceptions in them, then you probably won't see them happening. as a rule of thumb, don't do unity stuff on a different thread because that will generally make it fail silently
this is the whole snippet of code if the issue is elswhere here
yeah im only doing the stuff with gameobjects on the main thread, but I still want to see the exceptions of my fuckups
and my debug.logs
You were already answered
Oh my b somehow i did not see them
you are doing int / int, 90 / 100 is 0 (so 90 to 99 will always be 0, 100 to 111 will always be 1)
Ty!
await is not creating a new thread, i think you can see unity exception......
there should be some way to wait for a task finish also block main thread
i see this https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.start?view=net-8.0
no await doesnt create the thread
the task does
and the exceptions inside the task arent seen in the console
Awaiting waits for the task to finish and unwraps the exceptions that may have happened in it, so no await means no exceptions reported
Also valid if the async method you called returns void
I want to let the user work with an node graph at runtime. Is there any way to re-use anything from Unity here, or am I gonna have to hand-roll this (or find an asset)?
all the node graph stuff is in the editor assembly, no? so you'd probably have to hand roll it
yeah.
there is an asset in the store, but its pretty pricey iirc
I'm in a jam rn
I thought by putting the IF daisy chain in Awake, I can do the "if two buttons are pressed then use a special weapon and override their individual function" thing as a coroutine
But instead the program did their individual function and entirely didn't register the double input function
it won't be super elaborate. it'll basically be paths for events to flow through and a few nodes to respond to those events
this will not be turing complete, so help me god
i imagine it's not that hard if you're willing to accept some performance tradeoffs (e.g. reevaluating the entire graph every time you change anything)
and maybe not having the best ergonomics
I think you'd pretty much have to factor in some sort of delay
Please do elaborate
The two button input (overriding their original function) kind of works regarding to melee and boost when they are bunched together in a fixed update function
But at current state they don't work for some reason even when that if statement remained in a Start function (and if it's fixed update the game crashes immediately)
If A or B is pressed, wait 0.5 seconds before triggering ability A/B respectively. If the other key is also pressed in that timespan, trigger special ability.
It doesn't seem feasible that a human could consistently hit both keys in the same frame simultaneously, so a little delay would account for the timing issue
in my SRPG, I have party members
public class PartyMember
{
public BaseAlly Ally;
public Stats CurrentStats;
public PartyMember(BaseAlly ally)//Make a new party member based off ally defaults
{
Ally = ally;
CurrentStats = new Stats(ally.baseStats);
}
public PartyMember(BaseAlly ally, Stats stats)//Make a new party member with specific stats
{
Ally = ally;
CurrentStats = stats;
}
}```
and when I start a level spawn them I instantiate(PartyMember.ally) to the board and set it's stats to PartyMember.CurrentStats, my issue is, When the level is finished how do I go about properly updating the partymembers (I have stored in a list of partymembers in a scriptable object). my though was to have each PartyMember and BaseAlly have an ID and check if thoes match and copy the stats over if they do but im having trouble assigning the IDs properly and im not sure if thats the best way anyway
So I want a thought bubble to spawn above my character with text inside of the bubble, i have made a script that spawns the bubble and changes the text to what i want it to, but the text dosen't spawn inside the bubble
Idk if I'm setting it up wrong?
π 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.
and holy shit..
the file is too long
you should be using a JSON or XML
did you even read the bot text dawg/
also this belong in #π»βcode-beginner tbh
yeah everyone says that until it's proven otherwise xD
but anyhow, post the code properly please
the text is cutoff
that looks like ChatGPT crap
That's beacuse it is
lmao
flawed logic = gpt
no support for that crap here
Fast and works kinda?
clearly doesn't
yes, you generate crap then expect us to fix it for you
!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.
Aigth aigth, ill look up another solution i guess, got any ideas of how to make text and an object to spawn together?
spawn it at the same Vector2/3 position
general rule , WorldSpace and UI are on different coordinates
UI is screenspace
I've been using GPT to help me identify what the code I need to write does. You've still gotta debug it yourself but you can use it to get a general idea of how the code might operate
Or use world space ui
I'll look into it I guess
That's fine. The issue is usually:
Chat GPT would be useful in seeing how the ai implements something you've done or understand. It isn't so useful for beginners to learn with as they're likely going to be copying code blindly - likely not able to verify the ai solution. You can quickly produce risky error prone code with it though - usually at the expense of requesting debugging from others.
Goes with:
Tldr: Debugging AI solutions (suggestions) isn't favorable as anything and everything could be not working. || Minimum expectation is that the person writing the code knows what the code does (they've got to, they're the ones who wrote it) or have a tutorial to be evaluated. ChatGPT is confident and can be useful for generating error prone samples (quickly) but folks aren't wanting to be fixing AI mistakes - they'd rather try helping you understand a tutorial that's concrete (non changing) or expand your own knowledge (one step at a time and not simply having a lot of code with no insurance that any of it works). "Where did they get this from or who told them to write this" - which is often followed by "don't do it" not because it's being lazy but because nobody really wants to fix stuff that nobody really cared or bothered to make sure is working.||
Oh yeah absolutely. Completely agree which is why I've changed how I use it. I now get it to present me with three answers, one correct, two incorrect and I have to identify the correct code and why it's the correct solution.
Though of course 99% of people would ask it to do that job for them and then come here asking others to fix it π I understand why it's frowned upon generally speaking
I like GPT when I need randomly generated content
Like
give me a list of 40 random names comma separated
menial tasks are ok
That would be efficiently using the generator - and you'd know when he's done something wrong.
He's just doing the manual labor, you know what you're needing already.
chat gpt code is like a professional programmer on hallucinogenics
But this has also been a learning experience for me too π I'll be sure to make sure I've thoroughly understood anything it's created before I bring any code here. I have had a ton of luck getting it to create a GUIStyle Pause Menu that displays the last rendered frame on screen whilst pausing rendering in the background. I'm having such a blast with Unity in general right now
Maybe save the data to disk or have data that persists between scenes.
Assuming the complications of level completion refers to scene load and retaining data
Quick curiosity ,
does anyone know how to get TryGetComponent to work like GetComponentInParent ?
iirc with my testing it doesn't traverse up the hirerchy
write your own
ah.. thought I might..
thought so
annoyed typing
var parent = thing.GetComponentInParent<Foo>();
if(parent != null)
im getting null reference exception from this line. does anyone know why?
to be clear i did define playerCam
Player cam is null
nope
There is no camera with main camera tag in scene
there is
Camera.main would return null when there is no camera with main camera tag in scene.
You've got to check the tag.
The compiler is almost never wrong
looks fine
then its not present at the time the of the assignment in your script
The error possibly lies elsewhere - you haven't shown us the error from the console tab.
or that
alot of this
Human error is likely probable
this is line 64
Show us the player controller script
It should've been a move function call from the player controller that threw the error
this is my move function
How to post!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.
where does the camera assignment happen
hold on il paste this code i the thing
Also which is line 64
External code service is recommended
a powerful website for storing and sharing text and code snippets. completely free and open source.
when is OnStartClient called
the script is in a prefab it only exists after you connect
i dont see other explanation
nothing prevents anything from calling methods on prefabs
before instantiation, or instantiate disabled, call/init, enable
they need to be in the scene to call the update fuction no?
or is that not how unity works
since i wrote similar systems that hijack scene initialization my guess is that the framework youre using is loading first, disables all roots in the scene, performs init, then enables
probably easy to test if you add Debug.Break() in OnStartClient
and observe scene state
if the objects were disabled before awake, there wont be an awake until they are enabled again
similarly if you disable prefab before instantiation there wont be awake
your right
What are some troubleshooting methods to do to find out why a Class will not show in the inspector even if it is labeled with [Serializable]
update runs before start client
show the class declaration
using System;
using UnityEngine;
[Serializable]
public abstract class JobBase
{
public virtual string JobName => "No Name Job";
public virtual LevelingSystem LevelingSystem => new LevelingSystem();
}
Abstract classes aren't serializable?
To the Unity inspector that is.
abstract classes arent instantiatable
Ahhhhhhhh. shoot.
you cant create an instance of it
They wouldn't know what kind of child should be shown in the inspector
Should I go the ScriptableObject route then I guess...?
What is the jist of that?
So how could i do it to have a better game feel?
its only serialized within the same mono
no cross mono refs serialized
why is it abstract in the first place
Ill take a look into it.
or rather within the same serialized unity object
I don't see any abstract methods, this could very well be a regular class?
Uhhh. tbh not 100% sure. But i thought to build up the Base Job and then create all the differences within other scripts that inherit it
abstract is used to enforce that this class should only serve as a base for other
Yeah thats essentially what I was going for
can I use DontDestroyOnLoad in a way that when switching scenes (each has their own player object) and you go back to the first one the position remains?
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Job_Warrior : JobBase
{
public override string JobName => "Warrior";
}
its fine to not have any abstract methods in abstract class
I know its bare bones, but its what I was going for.
its also fine to treat it as a normal class, adding fields etc
the purpose still will be served
What do you mean?
you cant instantiate it, only inherit
yes, but we're not chatgpt
Like, the Job_Warrior class?
Maybe use scriptable objects to hold instances of job data and simply use a job component to reference these data?
Yeah, I feel like that might be easier for me honestly.
@unreal valley your entire problem is just that you added abstract. for what you wanted to do, it's not needed.
You'd forgo having to use polymorphism or inheritance simply to define data such as name and whatnot, that would do so through inline code.
how is that a problem
I was trying to be smarter than I actually am and was going for a OOP approach
More design friendly outside of pure code.
was refering to
it's not like OOP is wrong in this case, not required either though
abstract is a keyword for "do not use this, ONLY inherit"
So it's like an implicit interface?
honestly i don't even know why abstract exists, never used it
interfaces cant have non method members and implementations so no
Oh yeah
I honestly never used abstract
so i don't know much about it
I only learned about it because of our Java classes
Yeah im just going to scrap what I was doing and go with SciptableObjects lol
abstract methods are ment to be overridend xD
is it true that FindGameObjectWithTag is bad to use?
Just make a Job Class that grabs the data from the SO
@unreal valley and there you can use abstract
virutual methods can be override and also use the same code from the base function
abstract class Job : ScriptableObject
all Find methods are bad if used in Update, FixedUpdate or even some kind of loop
i'd actually recommend not using SO
what about Start and/or Awake?
It's fine
nice then π
As long as you don't spam it it's fine
the Find grows slower with amount of gameobjects in the scene
Im confused by this, why would I need it abstract at this point?
so you dont create instances of Job
if there are few references to be assigned, manually assign them unless the script have to store many references to GO
on accident, for example, youll enforce that only concrete Job implementations can be created
it simply a good practice that in case of data can save you some headache down the line
So do I want the Job an SO or the JobData an SO?
@unreal valley literally just erase "abstract" in your class and it'll work
idk why i need to repeat it so many times
i was meaning the backing data class, so JobData i guess in this case
I did, and it shows, but nothing is there.
for one there is nothing in the class to serialize
private void Awake()
{
Job_Warrior warrior = new();
jobs.Add(warrior);
foreach (JobBase job in jobs) jobNames.Add(job.JobName);
}
unity wont serialize properties and methods
not without [field:SerializeField] but its a bad practice imo
im having a weird issue when spawning a prefab. So basically I have a script that has the sole purpose of spawning a random sound effect player.
{
chooseClip();
createSoundSource(worldPosition);
soundSource.spatialize = true;
soundSource.maxDistance = maxDistanceFor3DSound;
if (randomizePitch)
{
soundSource.pitch = Random.Range(pitchRange.x, pitchRange.y);
}
soundSource.clip = chosenClip;
soundSource.Play();
Destroy(soundSource.gameObject,clipLength);
}
private AudioSource createSoundSource(Vector3 position)
{
GameObject g = Instantiate(new GameObject(),transform.position,quaternion.identity);
g.name = "soundPlayer";
soundSource = g.AddComponent<AudioSource>();
soundSource.playOnAwake = false;
soundSource.loop = false;
return soundSource;
}```
the issue that im having though is that it is *Also* Spawning a empty game object with nothing on it just named "new game object" ive isolated it to this script (if i dont call play audio it doesnt happen) but i cant see why its spawning two objects.