Unity中如何正确在字符串末尾追加数字实现对象重命名?
解决方案
可以用正则表达式匹配并提取现有副本编号,实现递增逻辑的同时加入长度限制处理,代码示例如下:
using System.Text.RegularExpressions; public static string GetNextCopyName(string originalName, int maxTitleLength = 60) { // 匹配末尾的 "- Copy (数字)" 格式 var match = Regex.Match(originalName, @" - Copy \((\d+)\)$"); if (match.Success) { // 提取当前编号并递增 int currentNum = int.Parse(match.Groups[1].Value); int nextNum = currentNum + 1; // 去掉原后缀,得到基础名称 string baseName = originalName.Substring(0, match.Index); // 构造新名称 string newName = $"{baseName} - Copy ({nextNum})"; // 检查长度,超出则截断基础名称 if (newName.Length > maxTitleLength) { int suffixLength = $" - Copy ({nextNum})".Length; int maxBaseLength = maxTitleLength - suffixLength; if (maxBaseLength > 0) { baseName = baseName.Substring(0, maxBaseLength).TrimEnd(); newName = $"{baseName} - Copy ({nextNum})"; } else { // 极端情况:后缀长度都超过限制,直接用简化名称 newName = $"Copy ({nextNum})"; } } return newName; } else { // 原名称无副本后缀,添加第一个副本标识 string newName = $"{originalName} - Copy (1)"; // 处理长度限制 if (newName.Length > maxTitleLength) { int suffixLength = " - Copy (1)".Length; int maxBaseLength = maxTitleLength - suffixLength; if (maxBaseLength > 0) { originalName = originalName.Substring(0, maxBaseLength).TrimEnd(); newName = $"{originalName} - Copy (1)"; } else { newName = "Copy (1)"; } } return newName; } }
用法示例
在创建新对象时直接调用这个方法:
// 假设你要复制的对象是targetObject targetObject.name = GetNextCopyName(targetObject.name, 50); // 第二个参数是你设定的标题最大长度
关键逻辑说明
- 正则匹配:用
@" - Copy \((\d+)\)$"精准匹配名称末尾的副本标识,只有符合格式的后缀才会被递增处理 - 编号递增:提取匹配到的数字,加1后重新构造后缀
- 长度限制处理:计算基础名称可保留的最大长度,截断后再拼接后缀;如果后缀本身就超过限制,会返回简化的副本名称,避免超出长度
- 兼容性:如果原名称的副本格式不规范(比如少括号、数字不是整数),会默认当作新对象处理,添加
- Copy (1)后缀
内容的提问来源于stack exchange,提问作者AmateurUnityDeveloper
相关产品推荐
相关产品推荐

